<?php

class Shop
{

	var $_allowed = array('.jpg','jpeg','.jpe','.gif','.png');
	var $_allowed_images = array('image/jpeg','image/pjpeg','image/jpe','image/gif','image/png','image/x-png');
	var $_coupon_limit = 10;
	var $_orders_limit = 10;
	var $_expander = 0;
	var	$_size = '%1$s%2$ux%3$u';
	const _size = '%1$s%2$ux%3$u';

	/**
	 * Стартовая страница административной части
	 */
	function shopStart($tpl_dir)
	{
		global $AVE_Template;

		$home = true;
		if (!empty($_REQUEST['sub']))
		{
			$home = false;
			switch ($_REQUEST['sub'])
			{
				case 'topseller':
					//$AVE_Template->assign('TopSeller', $this->topSeller('','',100));
					//$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_home_topseller.tpl'));
					break;

				case 'flopseller':
					//$AVE_Template->assign('TopSeller', $this->topSeller('','1',100));
					//$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_home_flopseller.tpl'));
					break;

				case 'rez':
					//$AVE_Template->assign('Rez', $this->getRez(100));
					//$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_rez100.tpl'));
					break;
			}
		}


		//$AVE_Template->assign('Correspond', $this->getCorrespond(100));
		//$AVE_Template->assign('admin_request', $this->get_admin_request(100));
		//$AVE_Template->assign('Rez', $this->getRez(10));
		//$AVE_Template->assign('TopSeller', $this->topSeller());
		//$AVE_Template->assign('FlopSeller', $this->topSeller(0,1));
		if ($home == true) $AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_home.tpl'));
	}

	/**
	 * вывод и редактирование начальных настроек
	 * внутри коммента старый вариант
	 */
	function Settings($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
/*
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
*/	
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
/*
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop
				SET
					Aktiv             = '" . (empty($_POST['Aktiv'])             ? '0'   : (int)$_POST['Aktiv']) . "',
					Waehrung          = '" . (empty($_POST['Waehrung'])          ? 'RUR' : htmlspecialchars(trim($_POST['Waehrung']))) . "',
					WaehrungSymbol    = '" . (empty($_POST['WaehrungSymbol'])    ? ''    : $_POST['WaehrungSymbol']) . "',
					Waehrung2         = '" . (empty($_POST['Waehrung2'])         ? ''    : $_POST['Waehrung2']) . "',
					WaehrungSymbol2   = '" . (empty($_POST['WaehrungSymbol2'])   ? ''    : $_POST['WaehrungSymbol2']) . "',
					Waehrung2Multi    = '" . (empty($_POST['Waehrung2Multi'])    ? ''    : $this->kreplace($_POST['Waehrung2Multi'])) . "',
					ShopLand          = '" . (empty($_POST['ShopLand'])          ? ''    : htmlspecialchars(strtoupper(trim($_POST['ShopLand'])))) . "',
					ArtikelMax        = '" . ((!empty($_POST['ArtikelMax']) && (int)$_POST['ArtikelMax'] > 2) ? (int)$_POST['ArtikelMax'] : '10') . "',
					KaufLagerNull     = '" . (empty($_POST['KaufLagerNull'])     ? '0'   : (int)$_POST['KaufLagerNull']) . "',
					VersandLaender    = '" . (empty($_POST['VersandLaender'])    ? ''    : implode(',', $_POST['VersandLaender'])) . "',
					VersFrei          = '" . (empty($_POST['VersFrei'])          ? '0'   : (int)$_POST['VersFrei']) . "',
					VersFreiBetrag    = '" . (empty($_POST['VersFreiBetrag'])    ? ''    : str_replace(',','.',$_POST['VersFreiBetrag'])) . "',
					GutscheinCodes    = '" . (empty($_POST['GutscheinCodes'])    ? ''    : $_POST['GutscheinCodes']) . "',
					ZeigeEinheit      = '" . (empty($_POST['ZeigeEinheit'])      ? ''    : $_POST['ZeigeEinheit']) . "',
					ZeigeNetto        = '" . (empty($_POST['ZeigeNetto'])        ? ''    : $_POST['ZeigeNetto']) . "',
					KategorienStart   = '" . (empty($_POST['KategorienStart'])   ? ''    : $_POST['KategorienStart']) . "',
					KategorienSons    = '" . (empty($_POST['KategorienSons'])    ? ''    : $_POST['KategorienSons']) . "',
					ZufallsAngebot    = '" . (empty($_POST['ZufallsAngebot'])    ? ''    : $_POST['ZufallsAngebot']) . "',
					ZufallsAngebotKat = '" . (empty($_POST['ZufallsAngebotKat']) ? ''    : $_POST['ZufallsAngebotKat']) . "',
					BestUebersicht    = '" . (empty($_POST['BestUebersicht'])    ? '0'   : (int)$_POST['BestUebersicht']) . "',
					Merkliste         = '" . (empty($_POST['Merkliste'])         ? ''    : $_POST['Merkliste']) . "',
					Topseller         = '" . (empty($_POST['Topseller'])         ? ''    : $_POST['Topseller']) . "',
					TemplateArtikel   = '" . (empty($_POST['TemplateArtikel'])   ? ''    : $_POST['TemplateArtikel']) . "',
					Vorschaubilder    = '" . (empty($_POST['Vorschaubilder'])    ? '80'  : intval($_POST['Vorschaubilder'])) . "',
					Topsellerbilder   = '" . (empty($_POST['Topsellerbilder'])   ? '40'  : intval($_POST['Topsellerbilder'])) . "',
					GastBestellung    = '" . (empty($_POST['GastBestellung'])    ? '0'   : (int)$_POST['GastBestellung']) . "',
					Kommentare        = '" . (empty($_POST['Kommentare'])        ? ''    : $_POST['Kommentare']) . "',
					KommentareGast    = '" . (empty($_POST['KommentareGast'])    ? ''    : $_POST['KommentareGast']) . "',
					ZeigeWaehrung2    = '" . (empty($_POST['ZeigeWaehrung2'])    ? '0'   : (int)$_POST['ZeigeWaehrung2']) . "',
					ShopKeywords      = '" . (empty($_POST['ShopKeywords'])      ? ''    : htmlspecialchars(trim($_POST['ShopKeywords']))) . "',
					ShopDescription   = '" . (empty($_POST['ShopDescription'])   ? ''    : htmlspecialchars(trim($_POST['ShopDescription']))) . "',
					required_intro    = '" . (empty($_POST['required_intro'])    ? '0'   : (int)$_POST['required_intro']) . "',
					required_desc     = '" . (empty($_POST['required_desc'])     ? '0'   : (int)$_POST['required_desc']) . "',
					required_price    = '" . (empty($_POST['required_price'])    ? '0'   : (int)$_POST['required_price']) . "',
					required_stock    = '" . (empty($_POST['required_stock'])    ? '0'   : (int)$_POST['required_stock']) . "'
				WHERE
					Id = '1'
			");
*/

			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop
				SET
					settings_active					='".(int)$_REQUEST['settings_active']."'
					settings_active_message			= '".clean_no_print_char($_REQUEST['ShopKeywords'])."'
					ShopKeywords 					= '".clean_no_print_char($_REQUEST['ShopKeywords'])."',
					ShopDescription 				= '".clean_no_print_char($_REQUEST['ShopDescription'])."',
					settings_not_in_stock			='".(int)$_REQUEST['settings_not_in_stock']."'
					settings_order_registering		='".(int)$_REQUEST['settings_order_registering']."'
					settings_use_coupon				='".(int)$_REQUEST['settings_use_coupon']."'
					settings_allow_comments			='".(int)$_REQUEST['settings_allow_comments']."'
					settings_allow_comments_guest	='".(int)$_REQUEST['settings_allow_comments_guest']."'
				WHERE
					Id = '1'
			");
		}

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop
			LIMIT 1
		");
		$row = $sql->FetchRow();
		//$row->VersandLaender = explode(',', $row->VersandLaender);
		
		$AVE_Template->caching = false;
		
		
		
		
		
		$AVE_Template->assign('row', $row);
		//$AVE_Template->assign('laender', $this->displayCountries());
		
		$content = array();
		$content['name'] = 'Настройки магазина';
		$content['html'] = $AVE_Template->fetch($tpl_dir . 'shop_settings.tpl');
		echo json_encode_cyr($content);
		exit;
	}

	//!	работает
	// темплейт кешируется
	function productCategs($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
								
			foreach ($_REQUEST['category_name'] as $id => $category_name)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_category
					SET
						category_name = '" . $category_name . "',
						category_dopname = '" . $_REQUEST['category_dopname'][$id] . "',
						PosiStartseite    = '" . $_REQUEST['PosiStartseite'][$id] . "'
					WHERE
						Id = '" . $id . "'
				");
			}
			$AVE_DB->clearcache('shop/shop_category');	
			$AVE_Template->templateCacheClear();
			exit;
		}
		
		
/*
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'savepos')
		{
		 	$result = $_REQUEST["item"];
		 	$i = 0;
		 	foreach($result as $value) {	
		 		$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_category SET PosiStartseite = '".$i."' WHERE Id = '".$value."'");
		 		$i++;
		 	}
		 	$AVE_DB->clearcache('shop_category');	
			$AVE_Template->templateCacheClear();
		 	exit;		
		}
*/
		

		$categs = array();
		if (!$AVE_Template->is_cached($tpl_dir . 'shop_categs.tpl', 'shop_category'))
		{
			$ProductCategs = $this->getCategoriesSimple(0, 1, $categs,'0');
			$AVE_Template->assign('ProductCategs', $ProductCategs);
		}
		$content = array();
		$content["name"] = 'Список существующих категорий';
		$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_categs.tpl', 'shop_category');

		//print_r($content);
		echo json_encode($content);
		exit;
		
		
	}



	//!	Работает
	function getCategoriesSimple($id, $prefix, &$entries, $admin=0, $dropdown=0, $navi=0){	
			global $AVE_DB;

			$sql = "SELECT * FROM " . PREFIX . "_modul_shop_category WHERE ".(($navi == '1') ? "Id" : "category_parent")." = '" . (int)$id . "' ORDER BY PosiStartseite ASC";
			$query = $AVE_DB->Query($sql, '1296000', 'shop/shop_category');
			
			if (!$query->numrows()) return;
				
				while ($item = $query->FetchRow())
				{
						$item->expander = $prefix;
						
						if($admin=='1'){
							 $item->navi = "<li><a href=''>".$item->category_name."</a></li>"; // навигация
							 $item->parents = $item->category_parent;
						}else{
							if($navi == '1' && $item->rub_on_link == '1'){
								$item->category_alias = '';
							 	$item->navi = " » <a href='".$item->category_alias."'>".$item->category_name."</a>";
							}elseif($navi != '1'){
								
							}else{
								$item = "";
							}
						}
						$entries[$item->Id] = $item;
						//array_push($entries,$item);
					//}
					//if($item->parent != 0) 
					//$this->getCategoriesSimple($item->parent, $entries, $navi, $admin);
					
					
					
					if ($admin == 1)
					{
						if($item->category_parent != 0 && $navi == '1'){
							$this->getCategoriesSimple($item->category_parent, $prefix, $entries, $admin, $dropdown, $navi);
						}	
					}
					else
					{
					
						$this->getCategoriesSimple($item->Id, (($dropdown == 1) ? $item->expander.'&nbsp;&nbsp;&nbsp;' : $prefix+1), $entries, $admin, $dropdown, $navi);			
					}					
					
					
					
				}
			return $entries;	
		}	





	//!	работает
	function translit($title, $return){
		$alias  = empty($title)  ? '' : prepare_url($title);
		if($return == 'return'){ return $alias;}
		elseif($return == 'echo'){ echo $alias;}
		exit;
	}





	//!	работает
	function editCateg($tpl_dir,$id)
	{
		global $AVE_DB, $AVE_Template;

		if($id>0){
			$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_category WHERE Id = '" . $id . "'")->FetchRow();
			$row->category_image_thumb = 	make_thumbnail(array("link" => $row->category_image, "size" => sprintf(self::_size, "c", "80", "80")));
			$content["name"] = "Редактирование категории";
		}else{
			$content["name"] = "Добавить новую категорию";
		}			
		
		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			@setcookie('LoadTab', '');
			
			$oper = 'INSERT';
			if($id>0) $oper = 'UPDATE';
			
			$zag = (($oper == 'UPDATE') ? "UPDATE " . PREFIX . "_modul_shop_category" : "INSERT INTO " . PREFIX . "_modul_shop_category");
			$where = (($oper == 'UPDATE') ? 'WHERE Id='.$id : '');
			

			
				$links = array();				
				$links = $this->getCategoriesSimple($row->category_parent, '', $links, '1', '0', '1');
				foreach($links as $value){
					$value_step1 = array_reverse(explode('/', $value->category_alias));
					$value_step2[] = $value_step1[0];
				}
				$value_step3 = array_reverse(explode('/', prepare_url(chop(((!empty($_REQUEST['category_alias'])) ? $_REQUEST['category_alias'] : $this->translit($_REQUEST['category_name'], 'return'))))));
				$value_step4 = "/".(($links) ? implode('/', array_reverse($value_step2))."/" : "").$value_step3[0];

			
			
				if($value_step4 != $row->category_alias){// при смене родительской ссылки обновляем детей
					
					$sql_c = $AVE_DB->Query("SELECT Id, category_alias FROM " . PREFIX . "_modul_shop_category WHERE category_alias LIKE '%".$row->category_alias."%'");
					while ($row_c = $sql_c->FetchRow()){
							$new_link = str_replace($row->category_alias, $value_step4, $row_c->category_alias);
						 	$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_category SET category_alias = '".$new_link."' WHERE Id = '" . $row_c->Id . "'");
					 }
			
					// так же  тут доделать продукты по образу и подобию
				
				
				
				}

			
			$sql = "
				$zag
				SET
					category_name         		= '" . clean_no_print_char($_REQUEST['category_name']) . "',
					category_description		= '" . mysql_escape_string($_REQUEST['category_description']). "',
					category_description2 		= '" . mysql_escape_string($_REQUEST['category_description2']) . "',
					PosiStartseite            	= '" . (int)$_REQUEST['PosiStartseite'] . "',
					category_image				= '" . clean_no_print_char($_REQUEST['category_image']) . "',
					category_parent           	= '" . ((!empty($_REQUEST['category_parent']) && is_numeric($_REQUEST['category_parent'])) ? $_REQUEST['category_parent'] : '0') . "',
					category_alias				= '" . $value_step4 . "',
					bid             			= '" . $_REQUEST['bid'] . "',
					cbid            			= '" . $_REQUEST['cbid'] . "'
				$where";
				$AVE_DB->Query($sql);


			$AVE_DB->clearcache('shop/shop_category');	
			$AVE_Template->templateCacheClear();

			exit;
		}
		
		
		
		$content = array();
		
		
		
		$oCKeditor = new CKeditor();
		$oCKeditor->returnOutput = true;
		$oCKeditor->config['height'] = 150;
		$oCKeditor->config['toolbar'] = 'cpengine_very_small';
		$config = array();
	
		$AVE_Template->assign('category_description', $oCKeditor->editor('category_description', stripslashes($row->category_description), $config));
		$AVE_Template->assign('category_description2', $oCKeditor->editor('category_description2', stripslashes($row->category_description2), $config));



	
		$categs = array();
		$ProductCategs = $this->getCategoriesSimple(0, '', $categs,'0', '1');
		$AVE_Template->assign('ProductCategs', $ProductCategs);
	


		$AVE_DB->clearcache('shop/shop_category');		
		$AVE_Template->templateCacheClear();
		
		$AVE_Template->assign('row', $row);
		$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_categ_edit.tpl');
		echo json_encode_cyr($content);
		exit;
	}

	//!	работает
	function delCateg($id)
	{
		global $AVE_DB, $AVE_Template;
		
		$query = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_category WHERE category_parent = '" . $id . "'");
		while ($item = $query->FetchRow())
		{
			$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_category WHERE Id = '" . $item->Id . "'");
			$this->delCateg($item->Id);
		}
		$query = $AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_category WHERE Id = '" . $id . "'");
		//echo '<script>window.reload();</script>';
		$AVE_DB->clearcache('shop/shop_category');	
		$AVE_Template->templateCacheClear();
		exit;
	}

	//!	эта функция пока отключена так как не сформирована таблица с товарами
	function CountItem($categ=0)
	{
		$categ = (int)$categ;
		$CountItem = $AVE_DB->Query("SELECT Id, product_category FROM " . PREFIX . "_modul_shop_product WHERE product_category = '" . $item->Id . "'AND product_active = 1")->NumRows();
		return $CountItem;
	}
	




	//!	работает
	function _getManufacturer()
	{
		global $AVE_DB;

		$manufacturer = array();
		$sql = "SELECT * FROM " . PREFIX . "_modul_shop_manufacturer ORDER BY manufacturer_name ASC";
		$query = $AVE_DB->Query($sql, '1296000', 'shop/manufacturer');
		while ($row = $query->FetchRow()) $manufacturer[] = $row;
		return $manufacturer;
	}


















/*
product_manufacturer
product_price
product_category
product_active
PosiStartseite
*/

	//!	в процессе редактирования - вроде работает
	function displayProducts($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

/*
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			foreach ($_POST['product_price'] as $id => $product_price)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_product
					SET
						product_price          = '" . $this->kReplace($product_price) . "',
						product_category          = '" . $_REQUEST['product_category'][$id] . "',
						PosiStartseite = '" . (int)$_REQUEST['PosiStartseite'][$id] . "'
					WHERE
						Id = '" . $id . "'
				");
			}

			header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=products&cp=" . SESSION);
			exit;
		}
*/
		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'savepos')
		{
			$start = get_current_page() * $_REQUEST['recordset'] - $_REQUEST['recordset'];
		 	$result = $_REQUEST["item"];
		 	$i = 0+$start;
		 	foreach($result as $value) {	
		 		$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_product SET PosiStartseite = '".$i."' WHERE Id = '".$value."'");
		 		$i++;
		 	}
		 	$AVE_DB->clearcache('shop/shop_product');	
		 	exit;		
		}		
		


/*
			$dbAct = '';
			reset ($_POST);
			while (list($key) = each($_POST))
			{
				if (isset($_REQUEST['SubAction']) && $_REQUEST['SubAction'] != 'nothing')
				{
					switch ($_REQUEST['SubAction'])
					{
						case 'close':
							$dbAct = "SET product_active = '0'";
							break;

						case 'open':
							$dbAct = "SET product_active = '1'";
							break;

						case 'del':
							$dbAct = "del";
							break;

						case '':
						default:
							$dbAct = '';
							break;
					}
				}

				if (substr($key,0,12) == "shopartikel_" && $dbAct != '')
				{
					$aktid = str_replace("shopartikel_","",$key);
					if ($dbAct == 'del')
					{
						$AVE_DB->Query("
							DELETE
							FROM " . PREFIX . "_modul_shop_product
							WHERE Id = '" . $aktid . "'
						");
					}
					else
					{
						$AVE_DB->Query("
							UPDATE " . PREFIX . "_modul_shop_product
							" . $dbAct . "
							WHERE Id = '" . $aktid . "'
						");
					}
				}
			}
*/



		
		
		
	$categs = array();
	$categ = $this->getCategoriesSimple(0, '', $categs, 0, 1);
	$AVE_Template->assign('ProductCategs', $categ);
	
	$AVE_Template->assign('products', $this->lastArticles($categ));
	$AVE_Template->assign('Manufacturer', $this->_getManufacturer());
		
		
		
	if(isset($_REQUEST['edit_adm']) && $_REQUEST['edit_adm'] == '1')
	{
		//$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_products_adm.tpl'));
	}else{
	//$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_products.tpl'));
		$content["name"] = 'Товары';
		//$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_products.tpl', 'shop_product', 'page-'.get_current_page());
		$AVE_Template->caching = false;
		$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_products.tpl');
	}

	//print_r($content);	
		//echo json_encode_cyr($content);
		echo json_encode($content);
		exit;

	}







	//!	вроде бы работает
	function lastArticles($categ)
	{
		global $AVE_DB, $AVE_Template;

		$limit = 10;

		$product_sales = '';
		$product_sales_navi = '';
		$product_warehouse = '';
		$product_warehouse_navi = '';
		$recordset_navi = '';
		$product_category = '';
		$product_category_navi = '';
		$product_manufacturer = '';
		$product_manufacturer_navi = '';
		$product_query = '';
		$product_query_navi = '';
		$product_price_query = '';
		$product_price_query_navi = '';
		$product_active = '';
		$product_active_navi = '';
		$product_status = '';
		$product_status_navi = '';
		
		
		$dopnav = ''; // хз что это такое
		

//print_r($_REQUEST);

		// я хз что это такое - не помню
		if (!empty($_REQUEST['Angebot']) && $_REQUEST['Angebot'] != 'egal')
		{
			$angebot = " AND a.Angebot = 1";
			$angebot_n = "&amp;Angebot=1";
		}


		/*
		по кол-ву продаж
		$_REQUEST['Bestellungen'] - $_REQUEST['product_sales']
		Bestellungen - product_sales
		$best - $product_sales
		$best_n - $product_sales_navi
		*/
		if (!empty($_REQUEST['product_sales']) && $_REQUEST['product_sales'] != 'egal')
		{
			$product_sales = " AND a.product_sales < '" . $_REQUEST['product_sales'] . "'";
			$product_sales_navi = "&amp;product_sales=" . $_REQUEST['product_sales'];
		}

		/*
		колличество на складе
		Lager - product_warehouse
		$lager - $product_warehouse
		$lager_n - $product_warehouse_navi
		*/
		if (!empty($_REQUEST['product_warehouse']) && $_REQUEST['product_warehouse'] != 'egal')
		{
			$product_warehouse = " AND a.product_warehouse < '" . $_REQUEST['product_warehouse'] . "'";
			$product_warehouse_navi = "&amp;product_warehouse=" . $_REQUEST['product_warehouse'];
		}


		// кол-во товаров выводить
		// нет смысла редактировать
		if (isset($_REQUEST['recordset']) && is_numeric($_REQUEST['recordset']))
		{
			if($_REQUEST['recordset'] > 100) $_REQUEST['recordset'] = '100';
			$limit = $_REQUEST['recordset'];
			$recordset_navi = "&amp;recordset=$_REQUEST[recordset]";
		}


		/*
		из какой категории выводить
		$_REQUEST['categ'] - $_REQUEST['product_category']
		KatId - product_category 
		KatId_Multi - product_category_multi
		$dbextra - $product_category
		$dbextra_n - $product_category_navi
		$product_categ_navi - categ - product_category
		*/
		if (isset($_REQUEST['product_category']) && is_numeric($_REQUEST['product_category']))
		{
			$product_category = " 
			AND (product_category = '" . $_REQUEST['product_category'] . "' 
			OR a.product_category_multi LIKE '%," . $_REQUEST['product_category'] . ",%' 
			OR a.product_category_multi LIKE '%," . $_REQUEST['product_category'] . "' 
			OR a.product_category_multi LIKE '" . $_REQUEST['product_category'] . ",%')";
			$product_category_navi = "&amp;product_category=" . $_REQUEST['product_category'];
		}


		/*
		$_REQUEST['manufacturer'] - $_REQUEST['product_manufacturer']
		Hersteller - product_manufacturer
		$manufacturer - $product_manufacturer
		$manufacturer_n - $product_manufacturer_navi
		*/
		if (isset($_REQUEST['product_manufacturer']) && is_numeric($_REQUEST['product_manufacturer']))
		{
			$product_manufacturer = " AND a.product_manufacturer = '" . $_REQUEST['product_manufacturer'] . "'";
			$product_manufacturer_navi = "&amp;product_manufacturer=" . $_REQUEST['product_manufacturer'];
		}



		/*
		контекстный поиск по артикулу, имени, описанию
		ArtNr - product_article
		ArtName - product_name
		TextKurz - product_small_description
		*/
		
		if (!empty($_REQUEST['product_query']))
		{
			$product_query = " 
			AND (a.product_article = '" . $_REQUEST['product_query'] . "' 
			OR a.product_name LIKE '%" . $_REQUEST['product_query'] . "%' 
			OR a.product_small_description LIKE '%" . $_REQUEST['product_query'] . "%')";
			$product_query_navi = "&amp;product_query=" . htmlentities(urlencode($_REQUEST['product_query']));
		}




		/*
		по цене от до
		$_REQUEST['price_start'] - $_REQUEST['product_price_start']
		$_REQUEST['price_end'] - $_REQUEST['product_price_end']
		Preis - product_price
		$price_query - $product_price_query
		$price_query_n - $product_price_query_navi
		*/

		if (isset($_REQUEST['product_price_start']) && is_numeric($_REQUEST['product_price_start']) &&
			isset($_REQUEST['product_price_end']) && is_numeric($_REQUEST['product_price_end']) &&
			$_REQUEST['product_price_start'] >= 0 && $_REQUEST['product_price_end'] >= 0 &&
			$_REQUEST['product_price_start'] < $_REQUEST['product_price_end'])
		{
			$product_price_query = " AND (a.product_price BETWEEN " . $_REQUEST['product_price_start'] . " AND " . $_REQUEST['product_price_end'] . ")";
			$product_price_query_navi = "&amp;product_price_start=" . $_REQUEST['product_price_start'] . "&amp;product_price_end=" . $_REQUEST['product_price_end'];
		}



		/* хз - лишнее - сортировка с категориями была выше
		if (isset($_REQUEST['product_categ']) && is_numeric($_REQUEST['product_categ']))
		{
			$product_categ = " AND a.KatId = '" . $_REQUEST['product_categ'] . "'";
			$product_categ_n = "&amp;product_categ=" . $_REQUEST['product_categ'];
		}
		*/




		/*
		активные документы или нет
		$_REQUEST['active'] - $_REQUEST['product_active']
		Aktiv - product_active
		active - product_active
		$active - $product_active
		$active_n - $product_active_navi
		*/
		if (isset($_REQUEST['product_active']) && $_REQUEST['product_active'] != 'all')
		{
			$product_active = " AND a.product_active = '" . $_REQUEST['product_active'] . "'";
			$product_active_navi = "&amp;product_active=" . $_REQUEST['product_active'];
		}







		// Sortierung

		//if (!empty($_REQUEST['sort']))
		//{
			switch ($_REQUEST['sort'])
			{
				case 'product_name_ASC':
					$db_sort = "ORDER BY a.product_name ASC";
					$navi_sort = "&sort=product_name_ASC";
					break;

				case 'product_name_DESC':
					$db_sort = "ORDER BY a.product_name DESC";
					$navi_sort = "&sort=product_name_DESC";
					break;

				case 'product_price_ASC':
					$db_sort = "ORDER BY a.product_price ASC";
					$navi_sort = "&sort=product_price_ASC";
					break;

				case 'product_price_DESC':
					$db_sort = "ORDER BY a.product_price DESC";
					$navi_sort = "&sort=product_price_DESC";
					break;
					
				case 'product_sales_ASC':
					$db_sort = "ORDER BY a.product_sales ASC";
					$navi_sort = "&sort=product_sales_ASC";
					break;

				case 'product_sales_DESC':
					$db_sort = "ORDER BY a.product_sales DESC";
					$navi_sort = "&sort=product_sales_DESC";
					break;

/*
LagerAsc - WarehouseAsc

				case 'WarehouseAsc':
					$db_sort = "ORDER BY a.product_warehouse ASC";
					$navi_sort = "&sort=WarehouseAsc";
					break;

				case 'WarehouseDesc':
					$db_sort = "ORDER BY a.product_warehouse DESC";
					$navi_sort = "&sort=WarehouseDesc";
					break;
*//*
GekauftAsc - SalesAsc
*/

				default:
					$db_sort = "ORDER BY a.PosiStartseite ASC";
					$navi_sort = "";
				break;
			}
		//}


		
		
		$shopitems = array();

		$sql = $AVE_DB->Query("
			SELECT
				a.Id
			FROM " . PREFIX . "_modul_shop_product as a
			WHERE a.Id != 0
			" . $angebot . "
			" . $product_sales . "
			" . $product_warehouse . " 
			" . $product_active . "
			" . $product_category . "
			" . $product_price_query . "
			" . $product_query . "
			" . $product_manufacturer . "
		");
		$num = $sql->NumRows();

		$limit = $limit;
		@$seiten = @ceil($num / $limit);
		$start = get_current_page() * $limit - $limit;

		$sql = "
			SELECT
				a.*,
				COUNT(comments.Id) AS comments,
				COUNT(wishlist.Id) AS wishlist
			FROM 
				" . PREFIX . "_modul_shop_product as a
			LEFT JOIN
				" . PREFIX . "_modul_shop_comments AS comments ON comments.comments_product_Id = a.Id
			LEFT JOIN
				" . PREFIX . "_modul_shop_wishlist AS wishlist ON wishlist.wishlist_product_Id = a.Id AND wishlist_send = 1
			WHERE a.Id != 0
			" . $angebot . "
			" . $product_sales . "
			" . $product_warehouse . "
			" . $product_active . "
			" . $product_category . "
			" . $product_price_query . "
			" . $product_query . "
			" . $product_manufacturer . "
			GROUP BY a.Id
			" . $db_sort . "
			LIMIT " . $start . "," . $limit;
		$query = $AVE_DB->Query($sql, '1296000', 'shop/shop_product');	


		while ($row = $query->FetchRow())
		{		

			@$row->maincateg = $categ[$row->product_category]->category_name;

			if(!empty($row->product_category_multi)){
				@$multi = explode(',', $row->product_category_multi);
				if (count($multi)>=1){ 
					foreach ($multi as $category_multi) {					
						if(!empty($category_multi)){
							@$mult['category_id'] = $categ[$category_multi]->Id;
							@$mult['category_name'] = $categ[$category_multi]->category_name;
							@$row->product_category_multi_parse[] = $mult;
						}
					}
				}
			}

			$row->ostatok = $row->product_warehouse - $row->product_reserve; // склад - резерв
			$row->product_image_thumb = make_thumbnail(array('link' => $row->product_image, 'size' => sprintf($this->_size, 'c', '40', '40')));
			// UPLOAD_SHOP_DIR."/".
			
			array_push($shopitems, $row);
		}


		/* хз что это такое - надо потом по ходу дела проверить*/
		/* 

		if (isset($_REQUEST['categ']) && is_numeric($_REQUEST['categ']))
		{
			$the_nav = $this->_getNavigationPath((int)$_REQUEST['categ'], '', '1', (int)$_REQUEST['navop']);
			define("TITLE_EXTRA", strip_tags($the_nav));
			$AVE_Template->assign('topnav', $this->_getNavigationPath((int)$_REQUEST['categ'], '', '1', (int)$_REQUEST['navop']));
		}
		if(isset($_REQUEST['edit_adm']) && $_REQUEST['edit_adm'] == '1')
		{	
			$dopnav = "&amp;edit_adm=1&amp;order=".$_REQUEST['order']."";
		}		
		
		if(isset($_REQUEST['edit']) && $_REQUEST['edit'] == '1')
		{	
			$dopnav2 = "&amp;edit=1&amp;pop=1";
		}
		*/		


		if ($num > $limit)
		{
			$page_nav = get_pagination($seiten, get_current_page()," <li><a class=\"pnav\" onclick=\"updateHash('tab4-1tab'); setupHash('widget2', this);\" href=\"#tab4-1tab\" rel=\"index.php?do=modules&action=modedit&mod=shop&moduleaction=products&cp=" . SESSION . $navi_sort . $angebot_n . $product_sales_navi . $recordset_navi . $product_category_navi . $product_manufacturer_navi . $product_query_navi . $product_price_query_navi . $product_active_navi . $dopnav . $dopnav2 ."&amp;page={s}\">{t}</a></li> ");
			$AVE_Template->assign("page_nav", $page_nav);
		}
		
	return $shopitems;
	}


	/*заменили на запрос sql*/
	/*
	function _getWishlist($id)
	{
		global $AVE_DB;
		$num = $AVE_DB->Query("
			SELECT
				Id
			FROM " . PREFIX . "_modul_shop_wishlist
			WHERE 
				to_send = 1 AND
				articles = '".(int)$id."'
			")->NumRows();
		return $num;		
	}
*/
	/*заменили на запрос sql*/
	/*	заменили на запрос sql
	function _getProductCommetary($id)
	{
		global $AVE_DB;
		$num = $AVE_DB->Query("
			SELECT
				Id
			FROM " . PREFIX . "_modul_shop_product_kommentare
			WHERE ArtId = '" . (int)$id . "'
		")->NumRows();
		return $num;
	}
*/






	// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!потом отредактировать!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	// редактирование комментариев
	function editComments($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		
			foreach ($_POST['Titel'] as $id => $Titel)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_product_kommentare
					SET
						Titel     = '" . $Titel . "',
						Kommentar = '" . $_POST['Kommentar'][$id] . "',
						Wertung   = '" . (($_POST['Wertung'][$id]<1 || $_POST['Wertung'][$id]>5) ? 3 : $_POST['Wertung'][$id]) . "',
						Publik    = '" . $_POST['Publik'][$id] . "'
					WHERE
						Id = '" . $id . "'
				");
			}

			if (isset($_REQUEST['Del']) && $_REQUEST['Del']>=1)
			{
			
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}				
			
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_product_kommentare WHERE Id = '" . $id . "'");
				}
			}

			echo '<script>window.opener.location.reload();window.close();</script>';
		}

		$comments = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_product_kommentare
			WHERE ArtId = '" . (int)$_REQUEST['Id'] . "'
			ORDER BY Id DESC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($comments, $row);
		}

		$AVE_Template->assign('comments', $comments);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_comments.tpl'));
	}


	
	/* пока убрали эту функцию за ненадобностью */
	/*

	function fetchShopNavi($noprint='')
	{
		global $AVE_Template;

//		$shopitems = array();
		$categs = array();
//		$fetchcat = (isset($_GET['categ']) && is_numeric($_GET['categ'])) ? $_GET['categ'] : '0';

		if ($noprint != 1)
		{
			$ShopCategs = $this->getCategoriesSimple(0, '', $categs,'0');
			$AVE_Template->assign('shopStart', $this->shopRewrite('index.php?module=shop'));
			$AVE_Template->assign('shopnavi', $ShopCategs);
			$AVE_Template->display($GLOBALS['mod']['tpl_dir'] . $this->_shop_navi);
		}
		else
		{
			$ShopCategs = $this->getCategoriesSimple(0, '', $categs,'0',1);

			return $ShopCategs;
		}

		return '';
	}





*/



	//! формирование даты
	function _create($data=0)
	{
		if (!empty($data)){
			$data = explode(" ", $data);
			$stamp[day] = explode(".", $data[0]);
			$stamp[time] = explode(":", $data[1]);
			
			if (!empty($stamp))
			{
				$timestamp = mktime(
					$stamp[time][0],
					$stamp[time][1],
					0,
					$stamp[day][1],
					$stamp[day][0],
					$stamp[day][2]
				);
			}
		}else{
			$timestamp = time();
		}
		return $timestamp;
	}	
	



	//!	 вроде бы работает, но потом надо отредактировать доп опции
	function editProduct($tpl_dir)
	{
		global $AVE_DB, $AVE_Template, $config_vars;

		$Id = ((isset($_REQUEST['Id']) && is_numeric($_REQUEST['Id'])) ? $_REQUEST['Id'] : '');

		$oper = 'INSERT';
		if($Id>0) $oper = 'UPDATE';
		
		$zag = (($oper == 'UPDATE') ? "UPDATE " . PREFIX . "_modul_shop_product" : "INSERT INTO " . PREFIX . "_modul_shop_product");
		$where = (($oper == 'UPDATE') ? 'WHERE Id='.$Id : '');



		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{

/*
Schlagwoerter - product_related - похожие товары
kReplace - заменяет , на .
Gewicht - product_weight - вес
Hersteller - product_manufacturer - производитель
Erschienen - product_published_start - публиковать с
Angebot - product_sel - рпспродажа
*/


			$q = "
				$zag
				SET
					product_article     			= '" . prepare_fname(clean_no_print_char($_REQUEST['product_article'])) . "',
					product_name         			= '" . clean_no_print_char($_REQUEST['product_name']) . "',
					product_active          		= '" . (int)@$_REQUEST['product_active'] . "',
					product_category        		= '" . (int)$_REQUEST['product_category'] . "',
					product_category_multi  		= '" . (empty($_REQUEST['product_category_multi']) ? '' : implode(',', $_REQUEST['product_category_multi']). ",") . "',
					product_small_description       = '" . clean_no_print_char($_REQUEST['product_small_description']) . "',
					product_description        		= '" . clean_no_print_char($_REQUEST['product_description']) . "',
					product_related   				= '" . $this->kReplace(clean_no_print_char($_REQUEST['product_related'])) . "',
					product_price           		= '" . $this->kReplace(clean_no_print_char($_REQUEST['product_price'])) . "',
					product_price_old      			= '" . $this->kReplace(clean_no_print_char($_REQUEST['product_price_old'])) . "',
					product_weight         			= '" . $this->kReplace(clean_no_print_char($_REQUEST['product_weight'])) . "',
					UstZone         = '" . ((!empty($_REQUEST['UstZone']) && is_numeric($_REQUEST['UstZone'])) ? $_REQUEST['UstZone'] : '0') . "',
					product_manufacturer      		= '" . (int)$_REQUEST['product_manufacturer'] . "',
					Einheit         = '" . $this->kReplace(chop($_REQUEST['Einheit'])) . "',
					EinheitId       = '" . $_REQUEST['EinheitId'] . "',
					product_warehouse           	= '" . clean_no_print_char($_REQUEST['product_warehouse']) . "',
					VersandZeitId   = '" . $_REQUEST['VersandZeitId'] . "',
					product_published_start      	= '" . $this->_create($_REQUEST['product_published_start']) . "',
					product_sel        				= '" . $_REQUEST['product_sel'] . "',
					product_top         			= '" . $_REQUEST['product_top'] . "',
					product_new         			= '" . $_REQUEST['product_new'] . "',
					product_dop_title_1    			= '" . clean_no_print_char(@$_REQUEST['product_dop_title_1']) . "',
					product_dop_title_2    			= '" . clean_no_print_char(@$_REQUEST['product_dop_title_2']) . "',
					product_dop_title_3    			= '" . clean_no_print_char(@$_REQUEST['product_dop_title_3']) . "',
					product_dop_title_4    			= '" . clean_no_print_char(@$_REQUEST['product_dop_title_4']) . "',
					product_dop_text_1     			= '" . clean_no_print_char(@$_REQUEST['product_dop_text_1']) . "',
					product_dop_text_2     			= '" . clean_no_print_char(@$_REQUEST['product_dop_text_2']) . "',
					product_dop_text_3     			= '" . clean_no_print_char(@$_REQUEST['product_dop_text_3']) . "',
					product_dop_text_4     			= '" . clean_no_print_char(@$_REQUEST['product_dop_text_4']) . "',
					DateiDownload   = '" . (empty($_REQUEST['DateiDownload'])   ? '' : $_REQUEST['DateiDownload']) . "',
					ProdKeywords    				= '" . clean_no_print_char($_REQUEST['ProdKeywords']) . "',
					ProdDescription 				= '" . clean_no_print_char($_REQUEST['ProdDescription']) . "',
					product_image					= '" . clean_no_print_char($_REQUEST['product_image']) . "',
					product_image_multi				= '" . (is_array($_REQUEST['feld']['9999999999']) ? serialize($_REQUEST['feld']['9999999999']) : '') . "'
				$where
			";
			
/*
,
					bid             = '" . ((!empty($_REQUEST['bid']) && is_numeric($_REQUEST['bid'])) ? $_REQUEST['bid'] : '0') . "',
					cbid            = '" . ((!empty($_REQUEST['cbid']) && is_numeric($_REQUEST['cbid'])) ? $_REQUEST['cbid'] : '0') . "'

*/

			$errors = '';

			$regex = '/[^\x20-\xFF]/';
			$regex_no_space = '/[^\x21-\xFF]/';
			
			if (empty($_REQUEST['product_name']) || preg_match($regex, $_REQUEST['product_name'])){ 
				$errors[] =  $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductName'];
			}
				
			if (empty($_REQUEST['product_article'])){
				$errors[] =  $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductNrS'];
			}	
				
			if (!empty($_REQUEST['product_article']) && !$this->_checkArtNumber($_REQUEST['product_article']) && $_REQUEST['product_article'] != $_REQUEST['product_article_old']){ 
				$errors[] = $GLOBALS['config_vars']['ProductNewArtnumberUnique'];
			}


			if(is_array($errors)){
				header( 'HTTP/1.1 500 Internal Server Error'); 
				echo json_encode($errors);
				exit;	
			}



			
			if (!is_array($errors))
			{
				$AVE_DB->Query($q);
				$lastid = (($oper == "INSERT") ? $AVE_DB->InsertId() : $Id);
				//$this->reportLog($_SESSION['user_name'] . ' - Отредактировал товар (' . stripslashes($_REQUEST['product_name']) . ')', 2, 2);
				$content["folder"] = "tab4-2";
				$content["id"] = "index.php?do=modules&action=modedit&mod=shop&moduleaction=edit_product&Id=".$lastid."&cp=". SESSION;
				echo json_encode($content);

			}
			exit;
		}


		if (!empty($Id)){


			$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_product WHERE Id = '" . $Id . "'")->FetchAssocArray();

			if($row['product_category_multi']) $row['product_category_multi'] = explode(',', $row['product_category_multi']);
			$row['product_image_thumb'] = make_thumbnail(array('link' => $row['product_image'], 'size' => sprintf($this->_size, 'c', '120', '120')));

		}	
		
			
			$product_category_multi_parse = get_field_bild_multi($row['product_image_multi'], "edit", "9999999999");
			$AVE_Template->assign('product_category_multi_parse', $product_category_multi_parse);	


			$oCKeditor = new CKeditor(); 
			$oCKeditor->returnOutput = true;
			$oCKeditor->config['height'] = 200;


			
			$oCKeditor->config['toolbar'] = 'cpengine_very_small';
			$config = array();
			$product_small_description = $oCKeditor->editor('product_small_description', @$row['product_small_description'], $config);	
			$AVE_Template->assign('product_small_description', $product_small_description);	

			$oCKeditor->config['toolbar'] = 'cpengine_small';
			$config = array();
			$product_description = $oCKeditor->editor('product_description', @$row['product_description'], $config);
			$AVE_Template->assign('product_description', $product_description);	


			for ($i = 1; $i<5; $i++)
			{
				$oCKeditor->config['height'] = 150;
				$oCKeditor->config['toolbar'] = 'cpengine_very_small';
				$config = array();
				
				$product_dop_text = 'product_dop_text_'.$i;
				$product_dop_text = $oCKeditor->editor('product_dop_text_'.$i, @$row['product_dop_text_'.$i], $config);	
				$AVE_Template->assign('product_dop_text_'.$i, $product_dop_text);
			}


		
		$content["name"] = 'Добавить новый товар';
		
	if (!empty($Id)){
		$AVE_Template->assign('row', $row);
		$content["name"] = 'Редактировать товар';
	}	
		$AVE_Template->assign('Manufacturer', $this->_getManufacturer());
		
		$categs = array();
		$categ = $this->getCategoriesSimple(0, '', $categs, 0, 1);
		$AVE_Template->assign('ProductCategs', $categ);		
		


		//$AVE_Template->assign('VatZones', $this->fetchVatZones());
		
		//$AVE_Template->assign('Units', $this->displayUnits());
		//$AVE_Template->assign('ShippingTime', $this->shippingTime());
		//$AVE_Template->assign('ProductCategs', $this->fetchShopNavi(1));
		//$AVE_Template->assign('esds', $this->fetchEsdFiles());
		//$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_product_edit.tpl'));
		
		
		
		$AVE_Template->caching = false;
		
		
		$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_product_edit.tpl');

//print_r($content);

		echo json_encode($content);
		exit;
	}





	//Проверка артикула товара на уникальность
	//!	работает
	function _checkArtNumber($artnumber)
	{
		global $AVE_DB;
		$sql = $AVE_DB->Query("SELECT product_article FROM " . PREFIX . "_modul_shop_product WHERE product_article = '" . $artnumber . "'LIMIT 1");
		$num = $sql->NumRows();
		if ($num == 1) return false;
		return true;
	}



	function _get_template($Id, $template1, $template2){
		global $AVE_DB;

		if (!empty($Id) && is_numeric($Id))
		{
			$row = $AVE_DB->Query("SELECT 
				category_parent, 
				template_categ_head,
				template_categ_item,
				template_products_head,
				template_products_item
				template_product_detail
			FROM " . PREFIX . "_modul_shop_category WHERE id = '" . $Id . "'")->fetchrow();
	
			if (!$item) return;
				

			
			//if(empty($item->$template1) && empty($item->$template2)){
			//	return $this->_get_template($item->category_parent, $template1, $template2);
			//}
	
			return $item;	
		}
	}	


	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! в работе
	function edit_template($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		
	
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save' && !empty($_REQUEST['category']) && is_numeric($_REQUEST['category']))
		{	
		
			$template_categ_head = ((!empty($_REQUEST['template_categ_head'])) ? ", template_categ_head = '" . clean_no_print_char($_REQUEST['template_categ_head']) . "'" : '');
			$template_categ_item = ((!empty($_REQUEST['template_categ_item'])) ? ", template_categ_item = '" . clean_no_print_char($_REQUEST['template_categ_item']) . "'" : '');
			$template_products_head = ((!empty($_REQUEST['template_products_head'])) ? ", template_products_head = '" . clean_no_print_char($_REQUEST['template_products_head']) . "'" : '');
			$template_products_item = ((!empty($_REQUEST['template_products_item'])) ? ", template_products_item = '" . clean_no_print_char($_REQUEST['template_products_item']) . "'" : '');
			$template_product_detail = ((!empty($_REQUEST['template_product_detail'])) ? ", template_product_detail = '" . clean_no_print_char($_REQUEST['template_product_detail']) . "'" : '');
			
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop_category
				SET
					cbid = '1'
					$template_categ_head
					$template_categ_item
					$template_products_head
					$template_products_item 
					$template_product_detail
				WHERE
					Id = '" . $_REQUEST['category'] . "'
			");					
		exit;
		}	
		
	
	
	
		$categs = array();
		$categ = $this->getCategoriesSimple(0, '', $categs, 0, 1);
		$AVE_Template->assign('ProductCategs', $categ);		

		if (!empty($_REQUEST['Id']) && is_numeric($_REQUEST['Id']))
		$row = $AVE_DB->Query("SELECT Id,category_parent, template_categ_head,template_categ_item,template_products_head,template_products_item,template_product_detail FROM " . PREFIX . "_modul_shop_category WHERE id = '" . $_REQUEST['Id'] . "'")->fetchrow();
		
		
		
		
		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'general')
		{	


			$content["name"] = "Редактирование шаблона вывода товаров";
		}
		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'detail')
		{	
		
		
		
			$content["name"] = "Редактирование детального шаблона вывода товара";
		}
		
		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'categ')
		{	

			
/*			
$row['templateItemCateg'] = "
id
name
parent_id
parent_name
navop_id
navop_name

descr_top
descr_bottom
image
position
prod_incateg
";
*/	
/*		
$row['template_head_categ']="content_level_(level | all)";		
*/			
			$content["name"] = "Редактирование шаблона вывода категорий";
		}		
		
		
		//print_r($row);
		$AVE_Template->assign('row', $row);
		$AVE_Template->caching = false;
		$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_template.tpl');

		//print_r($content);

		echo json_encode($content);
		exit;
	}












/*
	function displayVariantCategories()
	{
		global $AVE_DB;


		
		return $variantCateg;
	}
*/
	
	
	
	
	
	
	
	
	
	function variant_unique($name, $id = 0) {
	global $AVE_DB, $AVE_Template;
        $num = $AVE_DB->Query('SELECT Id FROM '.PREFIX.'_modul_shop_category_variant WHERE variant_property_name = "'.$name.'"'.(($id) ? ' AND Id <> '.$id : ''))->NumRows();
		if($num > 1) return $this->renameFile($name);
		return $name;
	}		
	
	function renameFile($file)
	{
		mt_rand();
		$rand = rand(11111,99999);
		$rn_file = $rand . '_' . $file;
		return $rn_file;
	}


	
	
	
	
	
	
	
	
	
	
	function variantsCategories($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;


		$Id = ((isset($_REQUEST['Id']) && is_numeric($_REQUEST['Id'])) ? $_REQUEST['Id'] : '');


		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'new')
		{

			$errors="";	
			
				$sql = $AVE_DB->Query("INSERT " . PREFIX . "_modul_shop_category_variant
					SET
						variant_name  				= '" . $_REQUEST['variant_name'] . "',
						variant_stop  				= '" . $_REQUEST['variant_stop'] . "',
						variant_sort  				= '" . $_REQUEST['variant_sort'] . "',
						variant_parent  			= '" . $_REQUEST['variant_parent'] . "',
						variant_property_name  		= '" . $this->translit($_REQUEST['variant_name'], 'return') . "',
						variant_active  			= '0',
						variant_product_category 	= '" . $_REQUEST['variant_product_category'] . "'");
				$AVE_Template->templateCacheClear();
				$AVE_DB->clearcache('shop/category_variant');
			exit;
		}
		
		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'del')
		{
			
			$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_category_variant WHERE Id = '" . $Id . "'");
			$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_category_variant WHERE variant_parent = '" . $Id . "'");
			$AVE_Template->templateCacheClear();
			$AVE_DB->clearcache('shop/category_variant');
			exit;
		}


		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		
		//print_r($_REQUEST['variant_name_Neu_2']);
		
			foreach ($_REQUEST['variant_name'] as $id => $variant_name)
			{
				if (!empty($variant_name))
				{
					$AVE_DB->Query("
						UPDATE " . PREFIX . "_modul_shop_category_variant
						SET
							variant_product_category 	= '" . @$_REQUEST['variant_product_category'][$id] . "',
							variant_name  				= '" . @$variant_name . "',
							variant_name_dop  			= '" . @$_REQUEST['variant_name_dop'][$id] . "',
							variant_property_name  		= '" . @$this->variant_unique($this->translit($variant_name, 'return')). "',
							variant_stop  				= '" . @$_REQUEST['variant_stop'][$id] . "',
							variant_search_small  		= '" . @$_REQUEST['variant_search_small'][$id] . "',
							variant_item_small  		= '" . @$_REQUEST['variant_item_small'][$id] . "',
							variant_item_detail  		= '" . @$_REQUEST['variant_item_detail'][$id] . "',
							variant_range  				= '" . @$_REQUEST['variant_range'][$id] . "',
							variant_sort  				= '" . @$_REQUEST['variant_sort'][$id] . "',
							variant_active 				= '" . @$_REQUEST['variant_active'][$id] . "'
						WHERE
							Id = '" . $id . "'
					"); 
				}
			}
		
			
 			foreach ($_REQUEST['variant_name_Neu_2'] as $new2_id => $variant_name)
			{
			
				if (!empty($variant_name))
				{
					$new2_id = (int)$new2_id;

					$AVE_DB->Query("
						INSERT " . PREFIX . "_modul_shop_category_variant
						SET
							variant_product_category 	= '" . $_REQUEST['variant_product_category_Neu_2'][$new2_id] . "',
							variant_name  				= '" . $variant_name . "',
							variant_name_dop  			= '" . $_REQUEST['variant_name_dop_Neu_2'][$new2_id] . "',
							variant_property_name  		= '" . $this->variant_unique(translit_string($_REQUEST['variant_name_Neu_2'][$new2_id]), $_REQUEST['variant_product_category_Neu_2'][$new2_id]). "',
							variant_stop  				= '" . $_REQUEST['variant_stop_Neu_2'][$new2_id] . "',
							variant_search_small  		= '" . $_REQUEST['variant_search_small_Neu_2'][$new2_id] . "',
							variant_item_small  		= '" . $_REQUEST['variant_item_small_Neu_2'][$new2_id] . "',
							variant_item_detail  		= '" . $_REQUEST['variant_item_detail_Neu_2'][$new2_id] . "',
							variant_range  				= '" . $_REQUEST['variant_range_Neu_2'][$new2_id] . "',
							variant_sort  				= '" . $_REQUEST['variant_sort_Neu_2'][$new2_id] . "',
							variant_parent 				= '".$new2_id."'
					"); 

 
				}
			}	
			
			
						
		//header('Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=variants_categories&cp=' . SESSION);
		$AVE_Template->templateCacheClear();
		$AVE_DB->clearcache('shop/category_variant');
		exit;		
		}
foreach ($_REQUEST['variant_name_Neu_2'] as $new2_id => $variant_name)
{

	if (!empty($variant_name))
	{
		$new2_id = (int)$new2_id;

		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_category_variant
			SET
				variant_product_category 	= '" . $_REQUEST['variant_product_category_Neu_2'][$new2_id] . "',
				variant_name  				= '" . $variant_name . "',
				variant_name_dop  			= '" . $_REQUEST['variant_name_dop_Neu_2'][$new2_id] . "',
				variant_property_name  		= '" . $this->variant_unique(translit_string($_REQUEST['variant_name_Neu_2'][$new2_id]), $_REQUEST['variant_product_category_Neu_2'][$new2_id]). "',
				variant_stop  				= '" . $_REQUEST['variant_stop_Neu_2'][$new2_id] . "',
				variant_search_small  		= '" . $_REQUEST['variant_search_small_Neu_2'][$new2_id] . "',
				variant_item_small  		= '" . $_REQUEST['variant_item_small_Neu_2'][$new2_id] . "',
				variant_item_detail  		= '" . $_REQUEST['variant_item_detail_Neu_2'][$new2_id] . "',
				variant_range  				= '" . $_REQUEST['variant_range_Neu_2'][$new2_id] . "',
				variant_sort  				= '" . $_REQUEST['variant_sort_Neu_2'][$new2_id] . "',
				variant_parent 				= '".$new2_id."'
		"); 


	}
}





		//$variantCateg = array();
		//$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_category_variant WHERE variant_parent = 0 ORDER BY variant_sort ASC, variant_name ASC");

/*
		while ($row = $sql->FetchRow())
		{

			$variantCateg_2 = array();
			$sql_2 = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_category_variant WHERE variant_parent = '" . $row->Id . "' ORDER BY variant_sort ASC, variant_name ASC");
		
    		while ($row_2 = $sql_2->fetchrow()) array_push($variantCateg_2, $row_2);
		
			$row->ebene_2 = $variantCateg_2;
		
			array_push($variantCateg,$row);
		}
*/		


if (!$AVE_Template->is_cached($tpl_dir . 'shop_category_variant.tpl', 'category_variant'))
{
		$variant = array();
		$AVE_Template->assign('variantCateg', $this->_get_category_variant('','',$variant));
		
		//print_r($this->_get_category_variant('','',$variant));
		
		$categs = array();
		$AVE_Template->assign('ProductCategs', $this->getCategoriesSimple(0, '', $categs, 0, 1));	
}		

		$content["name"] = "Свойства категорий";
		$content["html"] = $AVE_Template->fetch($tpl_dir . 'shop_category_variant.tpl', 'category_variant');
		//print_r($content);
		echo json_encode($content);
		exit;
	}






	function _get_category_variant($id, $prefix, &$entries)
	{
		global $AVE_DB;

		$variant = "
		SELECT * FROM " . PREFIX . "_modul_shop_category_variant 
		WHERE variant_parent= '". (int)$id ."' 
		ORDER BY variant_sort ASC, variant_name ASC";
		
		
		$query = $AVE_DB->Query($variant, '1296000', 'shop/category_variant');
		if (!$query->numrows()) return;
		$prefix++;
		while ($item = $query->FetchRow())
		{
			$item->prefix = $prefix;
			
			$entries[$item->Id] = $item;
			//if($item->variant_parent != '0'){
				//print_r(step2);
				$this->_get_category_variant($item->Id, $prefix, $entries);
			//}
		}		
		return $entries;	
	}






//
//	function newVariantsCategories()
//	{
//		global $AVE_DB;
//
//		$AVE_DB->Query("
//			INSERT " . PREFIX . "_modul_shop_varianten_kategorien
//			SET
//				Name  = '" . $_POST['Name'] . "',
//				stop  = '" . $_POST['stop'] . "',
//				sort  = '" . $_POST['sort'] . "',
//				ParentId  = '" . $_POST['parentNew'] . "',
//				KatId = '" . $_POST['KatId'] . "'
//		");
//
//		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=variants_categories&cp=" . SESSION);
//		exit;
//	}
//







//
//	function editVariantsCategory($tpl_dir,$id)
//	{
//		global $AVE_DB, $AVE_Template;
//
//		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
//		{
//				if($_SESSION['user_group'] !=1){
//				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
//				exit;
//			}			
//			$AVE_DB->Query("
//				UPDATE " . PREFIX . "_modul_shop_varianten_kategorien
//				SET Beschreibung = '" . $_POST['Beschreibung'] . "'
//				WHERE Id = '" . $id . "'
//			");
//
//			echo '<script>window.close()</script>';
//		}
//
//		$sql = $AVE_DB->Query("
//			SELECT *
//			FROM " . PREFIX . "_modul_shop_varianten_kategorien
//			WHERE Id = '" . $id . "'
//		");
//		$row = $sql->FetchRow();
//
//		$oFCKeditor = new FCKeditor('Beschreibung') ;
//		$oFCKeditor->Height = '400';
//		$oFCKeditor->ToolbarSet = 'Simple';
//		$oFCKeditor->Value	= $row->Beschreibung;
//		$Edi = $oFCKeditor->Create();
//
//		$AVE_Template->assign('Edi', $Edi);
//		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_variant_edit.tpl'));
//	}
//








/*
	function deleteVariantsCategory($id)
	{
		global $AVE_DB;

		$AVE_DB->Query("
			DELETE
			FROM " . PREFIX . "_modul_shop_varianten_kategorien
			WHERE Id = '" . $id . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=variants_categories&cp=" . SESSION);
		exit;
	}
*/


























































	//=======================================================
	// Rezensionen / Bewertungen (Рецензии / Оценки)
	//=======================================================
	function getRez($limit='')
	{
		global $AVE_DB;

		$L = (!empty($limit)) ? $limit : 10;
		$rez = array();
		$sql = $AVE_DB->Query("
			SELECT
				DISTINCT(ArtId)
			FROM " . PREFIX . "_modul_shop_product_kommentare
			WHERE Publik != 1
			LIMIT " . $L
		);

		while ($row = $sql->FetchRow())
		{
			$sql_a = $AVE_DB->Query("
				SELECT
					Id,
					ArtNr,
					ArtName
				FROM " . PREFIX . "_modul_shop_product
				WHERE Id = '" . $row->ArtId . "'
			");
			$row_a = $sql_a->FetchRow();
			@$row->Artname = $row_a->ArtName;
			@$row->ArtNr = $row_a->Id;
			array_push($rez,$row);
		}

		return $rez;
	}




	function get_admin_request($limit='')
	{
		global $AVE_DB;
		$L = ($limit != '') ? $limit : 100;
		$admin_request = array();
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_request_admin WHERE newa = '1' AND touser  = '".$_SESSION['user_id']."'  ORDER BY id DESC LIMIT $L");
		while($row = $sql->fetchrow())
		{
		
			$row->createusername  = ($row->createuser   == $_SESSION['user_id']) ? 'Вы' : $this->getUserName($row->createuser);
			$row->text = stripslashes($row->text);
			$row->date = date('d.m.Y H:i', $row->time);
		
		
		
			//$sql_order = $AVE_DB->Query("SELECT Id, Comment FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '".$row->orders."'");
			//$row_order = $sql_order->fetchrow();
			//$row->order = $row->orders;
			//$row->request = $row->request;
			//$row->Comment = $row_order->Comment;
			array_push($admin_request,$row);
		}
		return $admin_request;
	}		
	
	
	
	
	
	
	
	
	function getCorrespond($limit='')
	{
		global $AVE_DB;
		$L = ($limit != '') ? $limit : 100;
		$rez = array();
		$sql = $AVE_DB->Query("SELECT DISTINCT(orders), request, text FROM " . PREFIX . "_modul_shop_request_Correspond WHERE newa = '1' ORDER BY id DESC LIMIT $L");
		while($row = $sql->fetchrow())
		{
			$sql_order = $AVE_DB->Query("SELECT Id, Comment FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '".$row->orders."'");
			$row_order = $sql_order->fetchrow();
			$row->order = $row->orders;
			$row->request = $row->request;
			$row->Comment = $row_order->Comment;
			array_push($rez,$row);
		}
		return $rez;
	}	
	
	
	
	
	/**
	 * Настройки Магазина
	 *
	 * @param string $param название параметра
	 * @return mixed значение запрошенного параметра
	 */
	function _getShopSetting($param)
	{
		if (!isset($this->_setings))
		{
			global $AVE_DB;

			$this->_setings = $AVE_DB->Query("
				SELECT *
				FROM " . PREFIX . "_modul_shop
				LIMIT 1
			")->FetchRow();
		}

		return $this->_setings->$param;
	}

	//=======================================================
	// Dateiendung ermitteln (Определение типа файла по расширению)
	//=======================================================
	function getEndung($file)
	{
		$Endg = substr(strtolower($file),-4);
		switch ($Endg)
		{
			case '.jpg':
			case '.jpe':
			case 'jpeg':
			default :
				$End = 'jpg';
				break;

			case '.png':
				$End = 'png';
				break;

			case '.gif':
				$End = 'gif';
				break;
		}

		return $End;
	}




	function topSeller($type = '', $flop = '', $limit = 10)
	{
		global $AVE_DB;

		$topSeller = array();
		$db_categ = (!empty($_REQUEST['categ'])) ? " AND KatId = '" . $_REQUEST['categ'] . "'" : '';
		$AscDesc = ($flop == 1) ? 'ASC' : 'DESC';
		$sql = $AVE_DB->Query("
			SELECT
				Id,
				ArtNr,
				KatId,
				ArtName,
				TextKurz,
				Bild,
				Preis,
				Bestellungen
			FROM
				" . PREFIX . "_modul_shop_product
			WHERE Aktiv = 1
			AND Erschienen <= '" . time() . "'
			" . $db_categ . "
			ORDER BY Bestellungen " . $AscDesc . "
			LIMIT " . $limit
		);
		while ($row = $sql->FetchRow())
		{
			$row->Img = "";
			if (file_exists(BASE_DIR . '/modules/shop/thumbnails/shopthumb__' . $this->_getShopSetting('Topsellerbilder') . '__' . $row->Bild))
			{
				$row->Img = "<img src=\"../modules/shop/thumbnails/shopthumb__" . $this->_getShopSetting('Topsellerbilder') . "__" . $row->Bild . "\" alt=\"\" border=\"\" />";
			}
			else
			{
				$type = $this->getEndung($row->Bild);
				$row->Img = "<img src=\"../modules/shop/thumb.php?file=$row->Bild&amp;type=$type&amp;xwidth=" . $this->_getShopSetting('Topsellerbilder') . "\" alt=\"\" border=\"\" />";
			}

			$row->TextKurz = $row->Img . substr(strip_tags($row->TextKurz,'<b>,<strong>,<em>,<i>'), 0, 250) . '...';
			$row->Detaillink = 'index.php?module=shop&amp;action=product_detail&amp;product_id=' . $row->Id . '&amp;categ=' . $row->KatId . '&amp;navop=' . getParentShopcateg($row->KatId);
			array_push($topSeller, $row);
		}

		return $topSeller;
	}

	//=======================================================
	// Downloads einlesen (Файлы для скачивания)
	//=======================================================
	function fetchEsdFiles()
	{
		$verzname = BASE_DIR . '/modules/shop/files/';
		$dh = @opendir($verzname);
		$esds = array();
		while (@gettype($datei = @readdir($dh)) != @boolean)
		{
			if (@is_file("$verzname/$datei"))
			{
				if ($datei != "." && $datei != ".." && $datei != ".htaccess")
				{
					@array_push($esds, $datei);
				}
			}
		}
		@closedir($dh);

		return $esds;
	}

	//=======================================================
	// Wandelt eine falsche Eingabe um (10,50 in 10.5)
	//=======================================================
	function kReplace($string)
	{
		return str_replace(',', '.', $string);
	}

	function randomVar($c=0)
	{
		$transid = '';
		$chars = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
			'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',
			'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',
			'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z');
		$ch = ($c != 0) ? $c : 6;
		$count = count($chars) - 1;
		srand((double)microtime() * 1000000);
		for ($i = 0; $i < $ch; $i++)
		{
			$transid .= $chars[rand(0, $count)];
		}

		return(strtoupper($transid));
	}

	//=======================================================
	// Funktion zum umbenennen einer Datei (Функция переименовывания файлов)
	//=======================================================


	
	
	
	
	
	function _fetchusergroup($user)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("SELECT 
			g.Name,
			u.usergroup
			FROM 
				" . PREFIX . "_users as u,
				" . PREFIX . "_modul_shop_usergroup as g
			WHERE u.Id = '" . $user . "' AND
			u.usergroup = g.Id
			LIMIT 1");
		$row = $sql->FetchRow();
		$sql->Close();
		return (is_object($row) ? $row->Name : '');
	}	
	
	
	
	
	
	//=======================================================
	// Einen Hersteller auslesen (Выборка производителей)
	//=======================================================
	function _fetchManufacturer($Hersteller)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT Name
			FROM " . PREFIX . "_modul_shop_hersteller
			WHERE Id = '" . $Hersteller . "'
			LIMIT 1
		");
		$row = $sql->FetchRow();
		$sql->Close();

		return (is_object($row) ? $row->Name : '');
	}

	
	function displayusergroup()
	{
		global $AVE_DB;

		$manufacturer = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_usergroup
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($manufacturer, $row);
		}

		return $manufacturer;
	}

	
	


	function getUnit($Unit)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT Name
			FROM " . PREFIX . "_modul_shop_einheiten
			WHERE Id = '" . $Unit . "'
			LIMIT 1
		");
		$row = $sql->FetchRow();
		$sql->Close();

		return (is_object($row) ? $row->Name : '');
	}


	function fetchVatZones()
	{
		global $AVE_DB;

		$VatZones = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_ust
			ORDER BY Wert DESC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($VatZones, $row);
		}

		return $VatZones;
	}


	function displayPaymentMethods()
	{
		global $AVE_DB;

		$paymentMethods = array();
		$sql = $AVE_DB->Query("
			SELECT
				Id,
				Name
			FROM " . PREFIX . "_modul_shop_zahlungsmethoden
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($paymentMethods, $row);
		}

		return $paymentMethods;
	}


	function displayShippingMethods()
	{
		global $AVE_DB;

		$ShippingMethods = array();
		$sql = $AVE_DB->Query("
			SELECT
				Id,
				Name
			FROM " . PREFIX . "_modul_shop_versandarten
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($ShippingMethods, $row);
		}

		return $ShippingMethods;
	}


	function displayUnits()
	{
		global $AVE_DB;

		$Units = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_einheiten
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($Units, $row);
		}

		return $Units;
	}


	//=======================================================
	// Versand - Zeiten (Сроки доставки)
	//=======================================================
	function shippingTime()
	{
		global $AVE_DB;

		$shippingTime = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_versandzeit
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($shippingTime, $row);
		}

		return $shippingTime;
	}


	//=======================================================
	// Steuersдtze (Налоги)
	//=======================================================
	function vatZones($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Neu
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'new')
		{
			$AVE_DB->Query("
				INSERT " . PREFIX . "_modul_shop_ust
				SET
					Name = '" . $_POST['Name'] . "',
					Wert = '" . $this->kreplace($_POST['Wert']) . "'
			");
		}

		// Speichern
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			foreach ($_POST['Name'] as $id => $Name)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_ust
					SET
						Wert = '" . $this->kreplace($_POST['Wert'][$id]) . "',
						Name = '" . $Name . "'
					WHERE
						Id = '" . $id . "'
				");
			}
			// Lцschen
			if (isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_ust
						WHERE Id = '" . $id . "'
					");
				}
			}
		}

		$AVE_Template->assign('vatZones', $this->fetchVatZones());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_vatzones.tpl'));
	}


	//=======================================================
	// Datei - Downloads fьr einen Artikel (Файл - загрузки для товара)
	//=======================================================
	function esdDownloads($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Neu anlegen
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'new')
		{
			$AVE_DB->Query("
				INSERT INTO " . PREFIX . "_modul_shop_product_downloads
				SET
					ArtId        = '" . (!empty($_REQUEST['Id']) ? $_REQUEST['Id'] : '') . "',
					Datei        = '" . (!empty($_POST['Datei']) ? $_POST['Datei'] : '') . "',
					DateiTyp     = '" . (!empty($_POST['DateiTyp']) ? $_POST['DateiTyp'] : '') . "',
					TageNachKauf = '" . (!empty($_POST['TageNachKauf']) ? $_POST['TageNachKauf'] : '') . "',
					Bild         = '" . (!empty($_POST['Bild']) ? $_POST['Bild'] : '') . "',
					Titel        = '" . (!empty($_POST['Titel']) ? $_POST['Titel'] : '') . "',
					Beschreibung = '" . (!empty($_POST['Beschreibung']) ? $_POST['Beschreibung'] : '') . "',
					Position     = '" . (!empty($_POST['Position']) ? $_POST['Position'] : '') . "'
			");
		}

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		// Speichern
			if (isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach ($_POST['Del'] as $id => $Datei)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_product_downloads
						WHERE Id = '" . $id . "'
					");
				}
			}

			foreach ($_POST['Datei'] as $id => $Datei)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_product_downloads
					SET
						Datei        = '" . (!empty($Datei) ? $Datei : '') . "',
						DateiTyp     = '" . (!empty($_POST['DateiTyp'][$id]) ? $_POST['DateiTyp'][$id] : '') . "',
						TageNachKauf = '" . (!empty($_POST['TageNachKauf'][$id]) ? $_POST['TageNachKauf'][$id] : '') . "',
						Bild         = '" . (!empty($_POST['Bild'][$id]) ? $_POST['Bild'][$id] : '') . "',
						Titel        = '" . (!empty($_POST['Titel'][$id]) ? $_POST['Titel'][$id] : '') . "',
						Beschreibung = '" . (!empty($_POST['Beschreibung'][$id]) ? $_POST['Beschreibung'][$id] : '') . "',
						Position     = '" . (!empty($_POST['Position'][$id]) ? $_POST['Position'][$id] : '') . "'
					WHERE
						Id = '" . $id . "'
				");
			}
		}

		$downloads_full = array();
		$downloads_updates = array();
		$downloads_bugfixes = array();
		$downloads_other = array();

		$sql_full = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_product_downloads
			WHERE DateiTyp = 'full'
			AND ArtId = '" . $_REQUEST['Id'] . "'
			ORDER BY Position ASC
		");
		$sql_updates = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_product_downloads
			WHERE DateiTyp = 'update'
			AND ArtId = '" . $_REQUEST['Id'] . "'
			ORDER BY Position ASC
		");
		$sql_bugfixes = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_product_downloads
			WHERE DateiTyp = 'bugfix'
			AND ArtId = '" . $_REQUEST['Id'] . "'
			ORDER BY Position ASC
		");
		$sql_other = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_product_downloads
			WHERE DateiTyp = 'other'
			AND ArtId = '" . $_REQUEST['Id'] . "'
			ORDER BY Position ASC
		");

		while ($row_full = $sql_full->FetchRow()) array_push($downloads_full, $row_full);
		while ($row_updates = $sql_updates->FetchRow()) array_push($downloads_updates, $row_updates);
		while ($row_bugfixes = $sql_bugfixes->FetchRow()) array_push($downloads_bugfixes, $row_bugfixes);
		while ($row_other = $sql_other->FetchRow()) array_push($downloads_other, $row_other);

		$AVE_Template->assign('downloads_full', $downloads_full);
		$AVE_Template->assign('downloads_updates', $downloads_updates);
		$AVE_Template->assign('downloads_bugfixes', $downloads_bugfixes);
		$AVE_Template->assign('downloads_other', $downloads_other);

		$AVE_Template->assign('esds', $this->fetchEsdFiles());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_product_files.tpl'));
	}


	//=======================================================
	// Dateiupload-Funktion (Функция загрузки файлов)
	//=======================================================
	function uploadFile($maxupload=4000)
	{
		global $_FILES;

		$attach = "";
		define("UPDIR", BASE_DIR . "/attachments/");
		if (isset($_FILES['upfile']) && is_array($_FILES['upfile']))
		{
			for ($i=0;$i<count($_FILES['upfile']['tmp_name']);$i++)
			{
				if ($_FILES['upfile']['tmp_name'][$i] != "")
				{
					$d_name = strtolower(ltrim(rtrim($_FILES['upfile']['name'][$i])));
					$d_name = str_replace(" ","", $d_name);
					$d_tmp = $_FILES['upfile']['tmp_name'][$i];

					$fz = filesize($_FILES['upfile']['tmp_name'][$i]);
					$mz = $maxupload*1024;;

					if ($mz >= $fz)
					{
						if (file_exists(UPDIR . $d_name)) $d_name = $this->renameFile($d_name);
						@move_uploaded_file($d_tmp, UPDIR . $d_name);
						$attach[] = $d_name;
					}
				}
			}

			return $attach;
		}

		return '';
	}


	function showMoney($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
		if (isset($_REQUEST['search']) && $_REQUEST['search'] == 1)
		{
			$ZeitStart = mktime(0,0,1,$_REQUEST['start_Month'],$_REQUEST['start_Day'],$_REQUEST['start_Year']);
			$ZeitEnde = mktime(23,59,59,$_REQUEST['end_Month'],$_REQUEST['end_Day'],$_REQUEST['end_Year']);
		}
		else
		{
			$ZeitStart = mktime(0,0,1,date("m"),date("d")-(date("d")-1),date("Y"));
			$ZeitEnde = mktime(23,59,59,date("m"),date("d"),date("Y"));
		}

		$ZahlungsId = (isset($_REQUEST['ZahlungsId']) && $_REQUEST['ZahlungsId'] != 'egal') ? "AND ZahlungsId = '" . $_REQUEST['ZahlungsId'] . "'" : '';
		$VersandId = (isset($_REQUEST['VersandId']) && $_REQUEST['VersandId'] != 'egal') ? "AND VersandId = '" . $_REQUEST['VersandId'] . "'" : '';
		$Benutzer = (!empty($_REQUEST['Benutzer'])) ? "AND Benutzer = '" . $_REQUEST['Benutzer'] . "'" : '';

		$sql = $AVE_DB->Query("
			SELECT
				SUM(Gesamt) AS GesamtUmsatz
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE (Status = 'ok' || Status = 'ok_send')
			AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ")
			" . $ZahlungsId . "
			" . $VersandId . "
			" . $Benutzer
		);
		$row = $sql->FetchRow();

		$sql2 = $AVE_DB->Query("
			SELECT
				SUM(Gesamt) AS GesamtUmsatz
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ")
			" . $ZahlungsId . "
			" . $VersandId . "
			" . $Benutzer
		);
		$row2 = $sql2->FetchRow();

		$sql3 = $AVE_DB->Query("
			SELECT
				SUM(Gesamt) AS GesamtUmsatz
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE (Status = 'wait')
			AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ")
			" . $ZahlungsId . "
			" . $VersandId . "
			" . $Benutzer
		);
		$row3 = $sql3->FetchRow();

		$sql4 = $AVE_DB->Query("
			SELECT
				SUM(Gesamt) AS GesamtUmsatz
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE (Status = 'progress')
			AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ")
			" . $ZahlungsId . "
			" . $VersandId . "
			" . $Benutzer
		);
		$row4 = $sql4->FetchRow();

		$sql5 = $AVE_DB->Query("
			SELECT
				SUM(Gesamt) AS GesamtUmsatz
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE (Status = 'failed')
			AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ")
			" . $ZahlungsId . "
			" . $VersandId . "
			" . $Benutzer
		);
		$row5 = $sql5->FetchRow();

		$row->GesamtUmsatz = number_format($row->GesamtUmsatz,'2',',','.');
		$row->GesamtUmsatzAlle = number_format($row2->GesamtUmsatz,'2',',','.');
		$row->GesamtUmsatzWartend = number_format($row3->GesamtUmsatz,'2',',','.');
		$row->GesamtUmsatzBearbeitung = number_format($row4->GesamtUmsatz,'2',',','.');
		$row->GesamtFehlgeschlagen = number_format($row5->GesamtUmsatz,'2',',','.');

		$AVE_Template->assign('paymentMethods', $this->displayPaymentMethods());
		$AVE_Template->assign('shippingMethods', $this->displayShippingMethods());

		$AVE_Template->assign('row', $row);
		$AVE_Template->assign('ZeitStart', $ZeitStart);
		$AVE_Template->assign('ZeitEnde', $ZeitEnde);
		$AVE_Template->assign('currency', $this->_getShopSetting('WaehrungSymbol'));
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_money.tpl'));
	}

	//=======================================================
	//=======================================================
	// Bestellungen (ЗАКАЗЫ)
	//=======================================================
	//=======================================================
	function ZahlungsArt($id)
	{
		global $AVE_DB;

		//if(is_numeric($id)){
			$sql = $AVE_DB->Query("
				SELECT
					Name
				FROM " . PREFIX . "_modul_shop_zahlungsmethoden
				WHERE Id = '" . $id . "'
			");
			$row = $sql->FetchRow();
		//}else{
		//	$row->Name = $id."<br/><small>Robokassa</small>";
		//}		

		return $row->Name;
	}


	function VersandArt($id)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT
				Name
			FROM " . PREFIX . "_modul_shop_versandarten
			WHERE Id = '" . $id . "'
		");
		$row = $sql->FetchRow();

		return (is_object($row) ? $row->Name : '');
	}


	function getUserName($id)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT
				Vorname,
				Nachname
			FROM " . PREFIX . "_users
			WHERE Id = '" . $id . "'
		");
		$row = $sql->FetchRow();

		return (is_object($row) ? (substr($row->Vorname,0,1) . '. ' . $row->Nachname) : '');
	}


	function mailPage($tpl_dir,$orderid)
	{
		global $AVE_DB, $AVE_Template, $config_vars;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			$SystemMail = get_settings("mail_from");
			$SystemMailName = get_settings("mail_from_name");
			send_mail(
				$_REQUEST['mto'],
				stripslashes($_POST['Message']),
				$_POST['Subject'],
				$SystemMail,
				$SystemMailName,
				"html",
				$this->uploadFile(),
				1
			);
			echo '<script>window.close();</script>';
		}
		else
		{
			$sql = $AVE_DB->Query("
				SELECT *
				FROM " . PREFIX . "_modul_shop_bestellungen
				WHERE Id = '" . $orderid . "'
			");
			$row = $sql->FetchAssocArray();
			$row['ProductOrdersMailPreBody'] = $config_vars['ProductOrdersMailPreBody'];
			$row['ProductOrdersMailPreBody'] = str_replace("%N%", "\n", $row['ProductOrdersMailPreBody']);

			$UploadSize = @ini_get('upload_max_filesize');
			$PostSize = @ini_get('post_max_size');

			if (strtolower(@ini_get('file_uploads')) == 'off' || @ini_get('file_uploads') == 0)	$AVE_Template->assign('no_uploads', 1);

			$AVE_Template->assign('UploadSize', (($PostSize < $UploadSize) ? $PostSize : $UploadSize) );
			$AVE_Template->assign('row', $row);
			$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_mailpage.tpl'));
		}
	}


	function getArticleName($id)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_product
			WHERE Id = '" . $id . "'
		");
		$row = $sql->FetchRow();

		return $row;
	}


	function varCategory($id)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT Name
			FROM " . PREFIX . "_modul_shop_varianten_kategorien
			WHERE Id = '" . $id . "'
		");
		$row = $sql->FetchRow();

		return (is_object($row) ? $row->Name : '');
	}


	function splitVars($vars, $out = '')
	{
		global $AVE_DB;

		$v = explode(',', $vars);
		if (count($v)>=1)
		{
			foreach ($v as $var)
			{
				if ($var)
				{
					$sql = $AVE_DB->Query("
						SELECT *
						FROM " . PREFIX . "_modul_shop_varianten
						WHERE Id = '" . $var . "'
					");
					$row = $sql->FetchRow();
					$out .= '<b>' . $this->varCategory($row->KatId) . '</b>: ' . stripslashes($row->Name) . ' ' . $row->Operant . number_format($row->Wert, '2', ',', '.') . '<br />';
				}
			}
		}

		return $out;
	}

	
	
/* 	function Getdopshipper($id='', $shipper='')
	{
		global $AVE_DB;
		$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_dopshipper WHERE Id = '".$id."' AND versandarten = '".$shipper."'")->FetchRow();
		return $row;
	}	 */	
	
	
	
	
	
	
	
	
	
	
	//=======================================================
	// Alle Bestellungen (Все заказы)
	//=======================================================
	function showOrders($tpl_dir)
	{
	
		// search
		// generate
		global $AVE_DB, $AVE_Template;

		$Query = "";
		$Query_nav = "";
		$Betrag = "";
//		$Betrag_nav = "";
		$ZahlungsId = "";
		$ZahlungsId_nav = "";
		$VersandId = "";
		$VersandId_nav = "";
		$Order = "ORDER BY Id DESC";
		$Order_nav = "";
		
		$generate_sity = "";

		$za = $AVE_DB->Query("SELECT Number FROM " . PREFIX . "_modul_shop_order_zayavki ORDER BY Number DESC")->FetchRow();
		// Schnellstatus
		if (isset($_REQUEST['StatusOrder']) && $_REQUEST['StatusOrder'] != 'nothing')
		{
			reset ($_POST);
			while (list($key,/*$val*/) = each($_POST))
			{
				if (substr($key,0,7) == "orders_")
				{
					$aktid = str_replace("orders_","",$key);
					$AVE_DB->Query("
						UPDATE " . PREFIX . "_modul_shop_bestellungen
						SET Status = '" . $_REQUEST['StatusOrder'] . "'
						WHERE Id = '" . $aktid . "'
					");
				}
			}

			header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION);
			exit;
		}


		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'stoporder')
		{
					$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_bestellungen SET stop = '" . (int)$_REQUEST['value'] . "' WHERE Id = '" . (int)$_REQUEST['order'] . "'");
					//print_r("UPDATE " . PREFIX . "_modul_shop_bestellungen SET stop = '" . (int)$_REQUEST['value'] . "' WHERE Id = '" . (int)$_REQUEST['order'] . "'");

			exit;
		}

		// Sortierung
		if (!empty($_REQUEST['Order']))
		{
			switch ($_REQUEST['Order'])
			{
				case 'IdAsc': $Order = "ORDER BY Id ASC"; $Order_nav = "&Order=IdAsc"; break;
				case 'IdDesc': $Order = "ORDER BY Id DESC"; $Order_nav = "&Order=IdDesc"; break;
				case 'PaymentIdAsc': $Order = "ORDER BY ZahlungsId ASC"; $Order_nav = "&Order=PaymentIdAsc"; break;
				case 'PaymentIdDesc': $Order = "ORDER BY ZahlungsId Desc"; $Order_nav = "&Order=PaymentIdDesc"; break;
				case 'ShippingIdAsc': $Order = "ORDER BY VersandId ASC"; $Order_nav = "&Order=ShippingIdAsc"; break;
				case 'ShippingIdDesc': $Order = "ORDER BY VersandId Desc"; $Order_nav = "&Order=ShippingIdDesc"; break;
				case 'CustomerAsc': $Order = "ORDER BY Benutzer ASC"; $Order_nav = "&Order=CustomerAsc"; break;
				case 'CustomerDesc': $Order = "ORDER BY Benutzer Desc"; $Order_nav = "&Order=CustomerDesc"; break;
				case 'SummAsc': $Order = "ORDER BY Gesamt ASC"; $Order_nav = "&Order=SummAsc"; break;
				case 'SummDesc': $Order = "ORDER BY Gesamt Desc"; $Order_nav = "&Order=SummDesc"; break;
			}
		}



		/* 	бывший статус заказа	
				if (isset($_REQUEST['Status']) && $_REQUEST['Status'] != 'egal')
				{
					$Status = " AND Status = '" . $_REQUEST['Status'] . "'";
					$Status_nav = "&status=" . $_REQUEST['Status'];
				}
		*/
		
		/* статус заказа */
		$Status = '';
		$Status_nav = '';
		if(isset($_REQUEST['Status']) && strlen($_REQUEST['Status']) > 1)
		{
			$Status = " AND Status IN(";
			foreach($_REQUEST['Status'] as $value){
				$Status .= "'".$value."',";
				$Status_nav .= "&Status[]=" . $value;
			}
			$Status = @substr($Status,0,-1);
			$Status .= ")";
		}			
		

		if (!empty($_REQUEST['Query']))
		{
			$Query = " AND (Id = '" . $_REQUEST['Query'] . "' || TransId = '" . $_REQUEST['Query'] . "' || Benutzer = '" . $_REQUEST['Query'] . "' || Bestell_Email = '" . $_REQUEST['Query'] . "' || Liefer_Nachname = '" . $_REQUEST['Query'] . "' || Rech_Nachname = '" . $_REQUEST['Query'] . "') ";
			$Query_nav = "&Query=" . $_REQUEST['Query'];
		}

		if (!empty($_REQUEST['price_start']) && !empty($_REQUEST['price_end']))
		{
			$Betrag = " AND (Gesamt BETWEEN " . $this->kreplace($_REQUEST['price_start']) . " AND " . $this->kreplace($_REQUEST['price_end']) . ")";
//			$Betrag_nav = "&price_start=".$_REQUEST['price_start']."&price_end=".$_REQUEST['price_end'];
		}
		
		/* 	бывший вариант оплаты
		if (isset($_REQUEST['ZahlungsId']) && $_REQUEST['ZahlungsId'] != 'egal')
		{
			$ZahlungsId = " AND ZahlungsId = '" . $_REQUEST['ZahlungsId'] . "' ";
			$ZahlungsId_nav = "&ZahlungsId=" . $_REQUEST['ZahlungsId'];
		}
		*/
		
		/* вариант оплаты */
		if(isset($_REQUEST['ZahlungsId']) && strlen($_REQUEST['ZahlungsId']) > 1)
		{
			$ZahlungsId = " AND ZahlungsId IN(";
			foreach($_REQUEST['ZahlungsId'] as $value){
				$ZahlungsId .= $value.",";
				$ZahlungsId_nav .= "&ZahlungsId[]=" . $value;
			}
			$ZahlungsId = @substr($ZahlungsId,0,-1);
			$ZahlungsId .= ")";
		}			
		
		

		if (isset($_REQUEST['VersandId']) && $_REQUEST['VersandId'] != 'egal')
		{
			$VersandId = " AND VersandId = '" . $_REQUEST['VersandId'] . "' ";
			$VersandId_nav = "&VersandId=" . $_REQUEST['VersandId'];
		}
		
		if (isset($_REQUEST['start_Day']))
		{
			$ZeitStart = mktime(0,0,0,$_REQUEST['start_Month'],$_REQUEST['start_Day'],$_REQUEST['start_Year']);
			$ZeitStart_nav = "&start_Month=$_REQUEST[start_Month]&start_Day=$_REQUEST[start_Day]&start_Year=$_REQUEST[start_Year]";
		}
		else
		{
			$ZeitStart = (isset($_REQUEST['date']) && $_REQUEST['date'] == 'today') ? mktime(0,0,1,date("m"),date("d"),date("Y")) : mktime(0,0,1,date("m")-1,date("d"),date("Y"));
			$ZeitStart_nav = (isset($_REQUEST['date']) && $_REQUEST['date'] == 'today') ? "&amp;date=today" : "";
		}

		if (isset($_REQUEST['end_Day']))
		{
			$ZeitEnde = mktime(23,59,59,$_REQUEST['end_Month'],$_REQUEST['end_Day'],$_REQUEST['end_Year']);
			$ZeitEnde_nav = "&end_Month=" . $_REQUEST['end_Month'] . "&end_Day=" . $_REQUEST['end_Day'] . "&end_Year=" . $_REQUEST['end_Year'];
		}
		else
		{
			$ZeitEnde = mktime(23,59,59,date("m"),date("d"),date("Y"));
			$ZeitEnde_nav = "";
		}

		
		$ZeitSpanne = (isset($_REQUEST['search']) && $_REQUEST['search'] == 1 || isset($_REQUEST['date'])) ? "AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ") " : "";

		$ZeitStart2 = mktime(0,0,1,date("m"),date("d")-1,date("Y"));
		$ZeitEnde2 = mktime(23,59,59,date("m"),date("d"),date("Y"));
		
		$TimeStart = mktime(13,0,1,0,0,0);
		$TimeEnd = mktime(13,0,1,0,0,0);
		
		
		if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1')
		{		
		
			if (isset($_REQUEST['Land']) && $_REQUEST['Land'] != '')
			{
				$Land = " AND Liefer_Land = '" . $_REQUEST['Land'] . "'";
			}else{
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION);
				exit;			
			}
		
		
			if (isset($_REQUEST['start2_Day']) && isset($_REQUEST['start_Hour'])){
				$ZeitStart2 = mktime($_REQUEST['start_Hour'],0,1,$_REQUEST['start2_Month'],$_REQUEST['start2_Day'],$_REQUEST['start2_Year']);
			}else{
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION);
				exit;			
			}

			if (isset($_REQUEST['end2_Day']) && isset($_REQUEST['end_Hour'])){
				$ZeitEnde2 = mktime($_REQUEST['end_Hour'],0,1,$_REQUEST['end2_Month'],$_REQUEST['end2_Day'],$_REQUEST['end2_Year']);
			}else{
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION);
				exit;			
			}
		
/* 		
			if (isset($_REQUEST['start_Hour'])){
				$TimeStart = mktime($_REQUEST['start_Hour'],0,1,0,0,0);
			}else{
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION);
				exit;			
			}
			
			
			if (){
				$TimeEnd = mktime($_REQUEST['start_Hour'],0,1,0,0,0);
			}else{				
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION);
				exit;			
			}
		
		 */
		
		
	
		
		$ZeitSpanne = "AND (Datum BETWEEN " . $ZeitStart2 . " AND " . $ZeitEnde2 . ") ";
		$StopOrder = "AND stop != '1' ";
		
		
		}
//$Land		
//$ZeitSpanne		
		
		
		
		
		
		$Orders = array();
		$sql = $AVE_DB->Query("
			SELECT Id
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE Id != 0
			" . $VersandId . "
			" . $ZahlungsId . "
			" . $Betrag . "
			" . $Query . "
			" . $Land . "
			" . $Status . "
			" . $StopOrder . "
			" . $ZeitSpanne
		);
		$num = $sql->NumRows();

		if (!empty($_REQUEST['recordset']))
		{
			$limit = $_REQUEST['recordset'];
			$limit_nav = "&recordset=" . $_REQUEST['recordset'];
		}
		else
		{
			$limit = $this->_orders_limit;
			$limit_nav = "";
		}

		@$seiten = @ceil($num / $limit);
		$start = get_current_page() * $limit - $limit;

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE Id != 0
			" . $VersandId . "
			" . $ZahlungsId . "
			" . $Betrag . "
			" . $Query . "
			" . $Land . "
			" . $Status . "
			" . $StopOrder . "			
			" . $ZeitSpanne . "
			" . $Order . "
			LIMIT " . $start . "," . $limit
		);
		
/* 		
		if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1')
		{		
		
			print_r("
			SELECT *
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE Id != 0
			" . $VersandId . "
			" . $ZahlungsId . "
			" . $Betrag . "
			" . $Query . "
			" . $Land . "
			" . $Status . "
			" . $ZeitSpanne . "
			" . $Order . "
			LIMIT " . $start . "," . $limit);
		
		}		
		 */
		
		while ($row = $sql->FetchAssocArray())
		{
			$row['ArtikelS'] = "";
			$row['ArtikelSVars'] = "";
			$row['UserId'] = $row['Benutzer'];
			$Artikel = unserialize($row['Artikel']);
			$ArtikelVars = unserialize($row['Artikel_Vars']);
			if (is_array($Artikel))
			{
				$row['Gewicht'] = '0';
				foreach ($Artikel as $key => $value)
				{
					$art = $this->getArticleName($key);
					$row['ArtikelS'] .= "<br />$value x <a href=javascript:void(0) onclick=cp_pop(\'index.php?do=modules&action=modedit&mod=shop&moduleaction=edit_product&cp=" . SESSION . "&pop=1&Id=" . $key . "\',\'980\',\'740\',\'1\',\'edit_product\');>" . (is_object($art) ? ((strlen($art->ArtName)>60) ? substr($art->ArtName, 0, 60) . '...' : $art->ArtName) : '') . "</a>";
					$row['Gewicht'] += ($art->Gewicht * $value);
					
					if (is_array($ArtikelVars))
					{
						foreach ($ArtikelVars as $keys => $values)
						{
							if ($key == $keys) $row['ArtikelS'] .= "<br />" . $this->splitVars($values);
						}
					} // Ende Varianten
				} // Ende enthaltene Artikel
			}
			$row['request_number'] = md5(md5($row['Id'].$row['TransId'].$row['Benutzer'].$row['Datum']));
			$row['num_C'] = $AVE_DB->Query("SELECT * FROM ".PREFIX . "_modul_shop_request_Correspond WHERE request = '".$row['request_number']."' AND newa = '1'")->numrows();

			$row['usergroup'] = (is_numeric($row['Benutzer'])) ? $this->_fetchusergroup($row['Benutzer']) : 'Не зарегистрирован';
			
if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1' && !isset($_REQUEST['act']) && $_REQUEST['act'] != 'Сформировать акт')
{				
			if($row['VersandId'] == '5' && $row['ZahlungsId'] == '1'){
				$row['usluga'] = 'С24КО';
			}elseif($row['VersandId'] == '5' && $row['ZahlungsId'] != '1'){
				$row['usluga'] = 'С24';
			}elseif($row['VersandId'] == '3' && $row['ZahlungsId'] == '1'){
				$row['usluga'] = '24КО';
			}elseif($row['VersandId'] == '3' && $row['ZahlungsId'] != '1'){
				$row['usluga'] = '24';		
			}
			
			
			if($row['VersandId'] == '5' && $row['Liefer_Land'] == '337' && $row['DopShipperId'] == '32'){
				$row['metro'] = '1';
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '337' && $row['DopShipperId'] == '33'){
				$row['metro'] = '2';			
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '337' && $row['DopShipperId'] == '94'){
				$row['metro'] = '3';
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '337' && $row['DopShipperId'] == '95'){
				$row['metro'] = '5';
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '307' && $row['DopShipperId'] == '28'){
				$row['metro'] = '1'; // Пушкинская			
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '307' && $row['DopShipperId'] == '29'){
				$row['metro'] = '2'; //Севастопольская			
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '307' && $row['DopShipperId'] == '30'){
				$row['metro'] = '4';//братиславская 			
			}elseif($row['VersandId'] == '5' && $row['Liefer_Land'] == '307' && $row['DopShipperId'] == '31'){
				$row['metro'] = '3';//бауманская
			}			
			
			
/* 			
				VersandId
				5 	Самовывоз	
				3 	Курьер


				ZahlungsId		
				1 	При получении
										
				- 24   – доставка в течение 24 часов без приема наличных денег (безналичные заказы);
				- 24НАЛ – доставка в течение 24 часов с приемом наличных денег (Ваши чеки);
				- 24КО  – доставка в течение 24 часов с кассовым обслуживанием (Наши чеки. Агентский договор)
				- С24НАЛ – получение заказа в пункте самовывоза с приемом наличных денег (Ваши чеки)
				- С24КО - получение заказа в пункте самовывоза с кассовым обслуживанием (Наши чеки. Агентский договор).
				- С24 – получение оплаченного заказа в пункте самовывоза .
			 */
			
			
			
			
}			
			
			
			$row['N'] = $this->getUserName($row['Benutzer']);
			$row['Zahlart'] = $this->ZahlungsArt($row['ZahlungsId']);
			if($row['ZahlungsId'] == '25')$row['Zahlartcode'] = $row['ZahlungsIdcode'];
			$row['VersandArt'] = $this->VersandArt($row['VersandId']);
			$row['GenerateGesamt'] = $row['Gesamt'];
			$row['Gesamt'] = number_format($row['Gesamt'],'2',',','.');
			$row['BenId'] = (is_numeric($row['Benutzer'])) ? $row['Benutzer'] : '';
			$row['Benutzer'] = (is_numeric($row['Benutzer']) && ($row['Benutzer']>0) ) ? '<a href="javascript:void(0);" onclick="cp_pop(\'index.php?do=user&action=edit&Id=' . $row['Benutzer'] . '&cp=' . SESSION . '&pop=1\')">' . ( strlen($this->getUserName($row['Benutzer']))< 3 ? $row['Benutzer'] : $this->getUserName($row['Benutzer'])) . '</a>' : '<b>' . $row['Benutzer'] . '</b>';
			$row['BenutzerMail'] = '<a href="javascript:void(0);" onclick="cp_pop(\'index.php?do=modules&action=modedit&mod=shop&moduleaction=mailpage&OrderId=' . $row['Id'] . '&cp=' . SESSION . '&pop=1\')">E-Mail</a>';
			$row['DopShipper'] = $this->Getdopshipper($row['DopShipperId'], $row['VersandId'])->Name;
			$row['DopDopShipper'] = $this->Getdopshipper($row['DopDopShipperId'], $row['VersandId'])->Name;
			$row['sity'] = $this->Get_Count_Name($row['Liefer_Land']);
	
//Zahlart


	
			if (strlen($row['DopDopShipper']) > 10){			
				@preg_match("/(\w+)\s+(\d{2}).(\d{2})\s+(\w+)\s+(\d{2}).(\d{2})/", $row['DopDopShipper'], $kurier);
				$row['ot'] = $kurier[2];
				$row['do'] = $kurier[5];
			}

			if (strlen($row['DopShipper']) > 10){			
				@preg_match("/(\w+\s+\W\w+(\s|\w+)\w+\W)/", $row['DopShipper'], $samovivoz);
				$row['metroname'] = "Самовывоз ".$samovivoz[0];
			}

	
			array_push($Orders, $row);
		}

		$next_number = $za->Number+1;		
		
		if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1')
		{		
		
		$date = mktime(0,0,0,date("m"),date("d")+1,date("Y"));		
		$newdate = mktime(0,0,0,date("m"),date("d"),date("Y"));		

		}
				
	
		
		
		
		if ($num > $limit)
		{
			$page_nav = " <a class=\"pnav\" href=\"index.php?do=modules&action=modedit&mod=shop&moduleaction=showorders&cp=" . SESSION
				. "&page={s}" . ((isset($_REQUEST['search']) && $_REQUEST['search'] == 1) ? "&search=1" : "") .$Order_nav . $limit_nav . $VersandId_nav . $ZahlungsId_nav
				. $Query_nav . $Status_nav . $ZeitStart_nav . $ZeitEnde_nav . "\">{t}</a> ";
			$page_nav = get_pagination($seiten, 'page', $page_nav);
			$AVE_Template->assign('page_nav', $page_nav);
		}
		
		
		$AVE_Template->assign('newdate', $newdate);
		$AVE_Template->assign('date', $date);
		$AVE_Template->assign('number', $next_number);
		$AVE_Template->assign('available_countries', get_country_list(1));
		$AVE_Template->assign('Orders', $Orders);
		$AVE_Template->assign('ZeitStart', $ZeitStart);
		$AVE_Template->assign('ZeitEnde', $ZeitEnde);
		$AVE_Template->assign('ZeitStart2', $ZeitStart2);
		$AVE_Template->assign('ZeitEnde2', $ZeitEnde2);
		$AVE_Template->assign('TimeStart', $TimeStart);
		$AVE_Template->assign('TimeEnd', $TimeEnd);
		$AVE_Template->assign('usergroup', $this->displayusergroup());	
		$AVE_Template->assign('paymentMethods', $this->displayPaymentMethods());
		$AVE_Template->assign('shippingMethods', $this->displayShippingMethods());
		
		
		
	if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1' && isset($_REQUEST['save']) && $_REQUEST['save'] == '1' && !isset($_REQUEST['act']) && $_REQUEST['act'] != 'Сформировать акт')
	{		

		$Html = $AVE_Template->fetch($tpl_dir . 'shop_generate_orders.tpl');		

		$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_order_zayavki (
			Id,
			Number,
			Status,
			Land,
			TimeStart,
			TimeEnd,
			Orders,
			Html
		) VALUES (
			'', 
			'".$next_number."', 
			'".$_REQUEST['Status']."', 
			'".$_REQUEST['Land']."', 
			'".$ZeitStart2."', 
			'".$ZeitEnde2."', 
			'order', 
			'".addslashes($Html)."'
		)
		");	

	}		
		
		
		if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1' && isset($_REQUEST['act']) && $_REQUEST['act'] == 'Сформировать акт')
		{		
			$_SESSION['generate_act_order'] = '';
			$_SESSION['generate_act_order'] = $Orders;			
			include_once(BASE_DIR . '/modules/shop/class.generateact.php');
			$generateact = new generateact;
			$generateact->display3($tpl_dir, $next_number);
			
			$export_file = "act_".$next_number."_Hermes_Traide.gif";
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
			header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
			header ("Pragma: no-cache");
			header("Expires: 0");
			header('Content-Transfer-Encoding: windows-1251');
			header('Content-Disposition: attachment; filename="'.$export_file.'"');			
			exit;
		}
		
		
		if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == '1' && !isset($_REQUEST['act']) && $_REQUEST['act'] != 'Сформировать акт')
		{	
 			$export_file = "zayavka_".$next_number."_Hermes_Traide.xls";
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
			header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
			header ("Pragma: no-cache");
			header("Expires: 0");
			header('Content-Transfer-Encoding: windows-1251');
			header('Content-Type: application/vnd.ms-excel;'); // This should work for IE & Opera
			header('Content-Disposition: attachment; filename="'.$export_file.'"'); 
			echo $AVE_Template->fetch($tpl_dir . 'shop_generate_orders.tpl');
			exit;			
		}else{
			$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_orders.tpl'));
		}

	}

	
	
/* 	
function generateact($Orders, $next_number){

	if(!is_array($Orders)) exit;
	
	echo "<script>window.open('index.php?do=modules&action=modedit&mod=shop&moduleaction=generate107&cp=".SESSION."$act=".$next_number."&pop=1','generateact','left=0,top=0,width=600,height=800,scrollbars=1,resizable=1');</script>";
}	 */
	
	
	
	
	
	
	
	
	
	function showOrder_schet($id)
	{	
		global $AVE_DB, $AVE_Template;
		$row = $AVE_DB->Query("SELECT RechnungHtml FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '" . $id . "'")->FetchRow();
		//print_r($row);	
		$this->reportLog($_SESSION['user_name'] . ' - вывел счет заказа № '.$id.'', 2, 2);
		echo $row->RechnungHtml;
		exit;
	}
	
	
	
	
	
	function send_sms($to, $msg)
	{
		global $AVE_DB, $AVE_Template;
		$u = 'http://www.websms.ru/http_in5.asp';
		$msg = str_replace("<br/>","\n",$msg);
		$msg = urlencode($msg);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'Http_username=janty&Http_password=uWv7rtj5X&Phone_list='.$to.'&Message='.$msg);
		curl_setopt($ch, CURLOPT_URL, $u);
		$u = curl_exec($ch);
		curl_close($ch);
		$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_sender (id,text,data) VALUES ('', '".$u."', '".date("d.m.Y H:i")."')");
		return;
	}  




 













	
	
	
	
	
	// Einzelne Bestellung
	function showOrder($tpl_dir,$id)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '" . $id . "'")->FetchRow();

			$db_gesamt = (!empty($_REQUEST['Gesamt'])) ? ",Gesamt = '" . $this->kreplace($_REQUEST['Gesamt']) . "'" : "";



			
		$md5 = md5(md5($row->Id.$row->TransId.$row->Benutzer.$row->Datum));
			
		$this->reportLog($_SESSION['user_name'] . ' - Отредактировал заказ № '.$id.'', 2, 2);


		$final = "Спасибо за ваш заказ<br/>Мы рады вас видеть в лице наших клиентов";
			
	switch($_REQUEST['Status'])
	{		
		//1
		case 'progress':
			$admin_text = "Статус заказа:<br/>Ваш заказ №".$id." поступил в обработку.";
			$obr_pod_otp = "Datum2 = '".time()."', Datum3 = '', Datum4 = '',";
			$this->PostMessage($admin_text, $md5, $row->Phone, $row->Id, '1');
		break;
		
		//2
		case 'ok_send':
			// распилить питер и москву.
			//VersandId
			
			//if($row->Liefer_Ort == '337'){$date = $this->date_delivery('1');}
			//if($row->Liefer_Ort == '307'){$date = $this->date_delivery('2');}		

					
			$admin_text = ($row->VersandId == '5') ? (($row->Liefer_Ort == '337') ? "Статус заказа:<br/>Заказ №".$id." передан на точку самовывоза и уже доступен" : "Статус заказа:<br/>Заказ №".$id." передан на точку самовывоза и будет доступен завтра с 12.00") : "Статус заказа:<br/>Заказ №".$id." передан в службу доставки.";
			
			$obr_pod_otp = "Datum3 = '".time()."',";
			
			$this->PostMessage($admin_text, $md5, $row->Phone, $row->Id, '1');
			
			if($row->ZahlungsId != '1'){ // если не стоит при получении, значит расплатился - говорим спасибо
				$this->PostMessage($final, $md5, $row->Phone, $row->Id, '1');
			}

		break;

		//3
		case 'ok':
			$admin_text = "Статус заказа:<br/>Оплата за заказ №".$id." получена.";
			$obr_pod_otp = "Datum4 = '".time()."',";
			$this->PostMessage($admin_text, $md5, $row->Phone, $row->Id, '1');

			if($row->ZahlungsId == '1'){ // если стоит при получении - значит заказ доставлен уже и деньги получены - говорим спасибо
				$this->PostMessage($final, $md5, $row->Phone, $row->Id, '1');
			}	

			
		break;		

		
		case 'failed':
		
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
		
			$admin_text = "Статус заказа:<br/>Ваш заказ №".$id." отменен.";
			//$obr_pod_otp = "Datum4 = '".time()."',";
			$this->PostMessage($admin_text, $md5, $row->Phone, $row->Id, '1');
			
			$Artikel = unserialize($row->Artikel);
			if (is_array($Artikel))
			{
				foreach ($Artikel as $key => $value)
				{
					$parr = explode('_', $key);
					$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_product SET Bestellungen = Bestellungen-" . $value . ", Rezerv = Rezerv-" . $value . " WHERE Id = '" . $parr[0] . "'");
					unset($parr[0]);
					foreach ($parr as $par)
					{	
						$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_varianten SET Rezerv = Rezerv-" . $value . " WHERE Id = '" . $par . "'");
					}					
				}
			}			
		break;
	}
			//$row->VersandId == '7')
			//$admin_text = ($row->VersandId == '7') ? $this->getShopSetting('progress').$admin_text2 : $this->getShopSetting('progress');


		
/* 		case 'PayOk':
			$admin_text = "Статус заказа:<br/>Оплата за заказ №".$id." получена.";
			$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_request_Correspond(Id,user,request,text,time,orders,newa,newu) VALUES ('','admin','" . $md5 . "','" . $admin_text . "','" . time() . "','" . $row->Id . "','','1')");
			$obr_pod_otp = "Datum4 = '".time()."',";
		break; 
*/
		




			$Bez = ($_POST['Status'] == 'ok' || $_POST['Status'] == 'ok_send') ? time() : '';
			$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_bestellungen
				SET
					DatumBezahlt      = '" . $Bez . "',
					$obr_pod_otp
					NachrichtBenutzer = '" . $_POST['NachrichtBenutzer'] . "',
					NachrichtAdmin    = '" . $_POST['NachrichtAdmin'] . "',
					Status            = '" . $_POST['Status'] . "',
					RechnungText      = '" . $_POST['Text'] . "',
					RechnungHtml      = '" . $_POST['RechnungHtml'] . "'
					" . $db_gesamt . "
				WHERE
					Id = '" . $id . "'
			");	
			
/* 		 */	
			
			
			
			
			
			//if($_POST['Status'] == 'failed')
			//{
//
			//
			//}
			
			
//			$ArtikelVars = unserialize($row->Artikel_Vars);

/* 			// Mail an Kдufer senden
			if (isset($_REQUEST['SendMail']) && $_REQUEST['SendMail'] == 1)
			{
				$SystemMail = get_settings("mail_from");
				$SystemMailName = get_settings("mail_from_name");

				$_POST['Message'] = str_replace("%%ORDER_NUMBER%%", $row->Id, $_POST['Message']);

				send_mail(
					$row->Bestell_Email,
					stripslashes($_POST['Message'] . $_POST['Text']),
					$_POST['Subject'],
					$SystemMail,
					$SystemMailName,
					"text",
					$this->uploadFile()
				);
			}
 */
			echo '<script>window.opener.location.reload();window.close();</script>';
		}
		else
		{
			$sql = $AVE_DB->Query("
				SELECT *
				FROM " . PREFIX . "_modul_shop_bestellungen
				WHERE Id = '" . $id . "'
			");
			$row = $sql->FetchAssocArray();

			$oFCKeditor = new FCKeditor('RechnungHtml');
			$oFCKeditor->Height = '300';
			$oFCKeditor->ToolbarSet = 'Simple';
			$oFCKeditor->Value= $row['RechnungHtml'];
			$html = $oFCKeditor->Create();
			
$this->reportLog($_SESSION['user_name'] . ' - Решил глянуть заказик № '.$id.'', 2, 2);

			$row['IPC'] = $this->gethost($row['Ip']);
			$AVE_Template->assign('row', $row);
			$AVE_Template->assign('html', $html);
			$AVE_Template->assign('text', (!empty($row['RechnungText']) ? $row['RechnungText'] : ''));
			$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_order_edit.tpl'));
		}
	}

	
	
	
	
	function PostMessage($text, $md5, $phone, $order, $sms='')
	{
		global $AVE_DB, $AVE_Template;
	
		if($sms == '1' && strlen($phone) > 5){
			$vowels = array("-", "(", ")", " ");
			$phone = str_replace($vowels, "", $phone);
			
			$this->send_sms("+7".$phone, $text);
		}	
		
		$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_request_Correspond(Id,user,request,text,time,orders,newa,newu) VALUES ('','admin','" . $md5 . "','" . $text . "','" . time() . "','" . $order . "','','1')");
	}
	
	
	
	
	
	function markFailed($id, $pr)
	{
		global $AVE_DB, $AVE_Template;
		
				if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}

		//$AVE_DB->Query("
		//	UPDATE " . PREFIX . "_modul_shop_bestellungen
		//	SET Status = 'failed'
		//	WHERE Id = '" . $id . "'
		//");
		$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '" . $id . "'")->FetchRow();
			
		$md5 = md5(md5($row->Id.$row->TransId.$row->Benutzer.$row->Datum));

		$admin_text = "Статус заказа:<br/>Ваш заказ №".$id." отменен.";
		$this->PostMessage($admin_text, $md5, $row->Phone, $row->Id, '1');
		
		
		$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_bestellungen SET Status = 'failed', pr = '".$pr."' WHERE Id = '".$id."'");
		//echo '<script>window.opener.location.reload();window.close();</script>';
		
		$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '" . $id . "'")->FetchRow();
		$Artikel = unserialize($row->Artikel);
		if (is_array($Artikel))
			{
				//foreach ($Artikel as $key => $value)
				//{
				//	$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_product SET Rezerv = Rezerv-" . $value . " WHERE Id = '" . $key . "'");
				//}
					foreach ($Artikel as $key => $value)
					{
						$parr = explode('_', $key);
						$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_product SET Bestellungen = Bestellungen-" . $value . ", Rezerv = Rezerv-" . $value . " WHERE Id = '" . $parr[0] . "'");
						unset($parr[0]);
						foreach ($parr as $par)
						{	
							$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_varianten SET Rezerv = Rezerv-" . $value . " WHERE Id = '" . $par . "'");
						}						
					}				
				
				
				
				
			}		
	

		echo '<script>window.opener.location.reload();window.close();</script>';
	}	
	
	
	
	
	function set_user_group($id, $user)
	{
		global $AVE_DB;
/* 		print_r("
			UPDATE " . PREFIX . "_users
			SET usergroup = '".$id."'
			WHERE Id = '" . $user . "'
		");
 */		$AVE_DB->Query("
			UPDATE " . PREFIX . "_users
			SET usergroup = '".$id."'
			WHERE Id = '" . $user . "'
		");
		exit;;
	}



	/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! мне кажется я эту функцию убрал !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
	/*
	function newCateg($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Speichern
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}		
		
			$DbImage = '';
			$upload_dir = BASE_DIR . '/modules/shop/uploads/';

			if (!empty($_FILES['Bild']['tmp_name']))
			{
				$name = str_replace(array(' ', '+','-'),'_',strtolower($_FILES['Bild']['name']));
				$name = preg_replace("/__+/", "_", $name);
//				$temp = $_FILES['Bild']['tmp_name'];
//				$endung = strtolower(substr($name, -3));
				$fupload_name = $name;

				if (in_array($_FILES['Bild']['type'], $this->_allowed_images))
				{
					// Wenn Bild existiert, Bild umbenennen
					if (file_exists($upload_dir . $fupload_name))
					{
						$fupload_name = $this->renameFile($fupload_name);
						$name = $fupload_name;
					}

					// Bild hochladen
					@move_uploaded_file($_FILES['Bild']['tmp_name'], $upload_dir . $fupload_name);
					@chmod($upload_dir . $fupload_name, 0777);

					$DbImage = $fupload_name;
				}
			}
			$AVE_DB->Query("
				INSERT " . PREFIX . "_modul_shop_category
				SET
					category_parent           = '" . ((!empty($_POST['category_parent']) && is_numeric($_POST['category_parent'])) ? $_POST['category_parent'] : '0') . "',
					category_name         = '" . $_POST['category_name'] . "',
					category_description = '" . $_POST['category_description'] . "',
					Rang            = '" . ((!empty($_POST['Rang']) && is_numeric($_POST['Rang'])) ? $_POST['Rang'] : '1') . "',
					Bild            = '" . $DbImage . "',
					bid             = '" . ((!empty($_POST['bid']) && is_numeric($_POST['bid'])) ? $_POST['bid'] : '0') . "',
					cbid            = '" . ((!empty($_POST['cbid']) && is_numeric($_POST['cbid'])) ? $_POST['cbid'] : '0') . "'
			");

			echo '<script>window.opener.location.reload(); window.close();</script>';
		}

		$oFCKeditor = new FCKeditor('category_description') ;
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Basic';
		$oFCKeditor->Value	= @$_POST['category_description'];
		$category_description = $oFCKeditor->Create();

		$AVE_Template->assign('category_description', $category_description);
		$AVE_Template->assign('ProductCategs', $this->fetchShopNavi(1));
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_categ_new.tpl'));
	}
	*/

	
	/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! скорее всего мы это больше не используем !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
	function get_grp_ptr($id, $type = '')
	{
		global $AVE_DB, $AVE_Template;
	
	
		$id   = (int)$id;
		$type = trim($type);
		if (!$id) return FALSE;
		
		$query = $AVE_DB->Query("SELECT PT.*, P.* FROM "
		    .PREFIX."_modul_shop_properties_table AS PT"
		    ." LEFT JOIN ".PREFIX."_modul_shop_properties AS P ON P.group_id=".$id." AND P.property_id=PT.id"
		    ." WHERE P.property_id IS "
		    .('NOT' == $type ? '' : 'NOT ')."NULL"
		    ." ORDER BY ".('NOT' == $type ? "PT.id " : 'P.ord'));
		$checked = 'NOT' == $type ? '' : ' checked';
		$ret = array();
		while($row = $query->fetchrow())
		{
				    $row->prt_id = $row->id;
				    $row->prt_name = $row->property_title;
				    $row->prt_prefix = $row->property_prefix ? $row->property_prefix : '&nbsp;';
				    $row->prt_suffix = $row->property_suffix ? $row->property_suffix : '&nbsp;';
				    $row->prt_type = $row->type;
				    $row->prt_ord = $row->ord ? $row->ord : '0';
				    $row->prt_item_small_ord = $row->item_small_ord ? $row->item_small_ord : '0';
				    $row->checked = $checked;
				    $row->search_checked = $row->search ? 'checked' : '';
				    $row->search_small_checked = $row->search_small ? 'checked' : '';
					$row->item_small_checked = $row->item_small ? 'checked' : '';
				    $row->range_checked = $row->range ? 'checked' : '';
		array_push($ret, $row);
		}
	return $ret;
	}	

	
	
	/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! непонятно назначение этой функции !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
	function delCategCall($id)
	{
		$this->delCateg($id);

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=product_categs&cp=" . SESSION);
		exit;
	}












	//=======================================================
	// Gutschein - Codes (Купоны на скидку)
	//=======================================================
	function getOrderDate($id)
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT Datum
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE Id = '" . $id . "'
		");
		$row = $sql->FetchRow();

		return (is_object($row) ? $row->Datum : '0');
	}

	// Neuer Code
	function couponCodesNew()
	{
		global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_gutscheine
			SET
				Code         = '" . $_POST['Code'] . "',
				Prozent      = '" . $this->kReplace($_POST['Prozent']) . "',
				Mehrfach     = '" . $_POST['Mehrfach'] . "',
				AlleBenutzer = '" . $_POST['AlleBenutzer'] . "',
				GueltigVon   = '" . @mktime(0,0,0,date("m"),date("d")-1,date("Y")) . "',
				GueltigBis   = '" . @mktime(23,59,59,date("m")+1,date("d"),date("Y")) . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=couponcodes&cp=" . SESSION);
		exit;
	}

	// Anzeigen
	function couponCodes($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Lцschen
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			if (isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_gutscheine
						WHERE Id = '" . $id . "'
					");
				}
			}
			// Speichern
			$regex_birthday = '#(0[1-9]|[12][0-9]|3[01])([[:punct:]| ])(0[1-9]|1[012])\2(19|20)\d\d#';
			foreach ($_POST['Code'] as $id => $Code)
			{
				if (@preg_match($regex_birthday, $_POST['GueltigVon'][$id]) &&
					@preg_match($regex_birthday, $_POST['GueltigBis'][$id]))
				{
					$gueltig_von = explode('.', $_POST['GueltigVon'][$id]);
					$gueltig_bis = explode('.', $_POST['GueltigBis'][$id]);

					$gvon = @mktime(0,0,0,$gueltig_von[1],$gueltig_von[0],$gueltig_von[2]);
					$gbis = @mktime(23,59,59,$gueltig_bis[1],$gueltig_bis[0],$gueltig_bis[2]);

					$DB_von_bis = ",GueltigVon = '" . $gvon . "', GueltigBis = '" . $gbis . "' ";
				}
				else
				{
					$DB_von_bis = "";
				}

				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_gutscheine
					SET
						Code         = '" . $Code . "',
						Prozent      = '" . $this->kReplace($_POST['Prozent'][$id]) . "',
						Mehrfach     = '" . $_POST['Mehrfach'][$id] . "',
						AlleBenutzer = '" . $_POST['AlleBenutzer'][$id] . "'
						" . $DB_von_bis . "
					WHERE
						Id = '" . $id . "'
				");
			}
		}

		// Auslesen
		$couponCodes = array();
		$sql = $AVE_DB->Query("
			SELECT
				Id
			FROM " . PREFIX . "_modul_shop_gutscheine
		");
		$num = $sql->NumRows();

		$limit = $this->_coupon_limit;
		@$seiten = @ceil($num / $limit);
		$start = get_current_page() * $limit - $limit;

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_gutscheine
			LIMIT " . $start . "," . $limit
		);

		while ($row = $sql->FetchRow())
		{
			$row->BIdLink = '';
			$BestellIds = explode(',', $row->BestellId);
			foreach ($BestellIds as $BId)
			{
				if ($BId != '')
				{
					$row->BIdLink .= '<a href=\'javascript:void(0);\' onclick=cp_pop(\'index.php?do=modules&action=modedit&mod=shop&moduleaction=showorder&cp=' . SESSION . '&Id=' . $BId . '&pop=1\',\'980\',\'740\',\'1\',\'show_order\')>' . date("d.m.Y, H:i", $this->getOrderDate($BId)) . '</a><br />';
				}
			}

			$row->GueltigVon = date('d.m.Y', $row->GueltigVon);
			$row->GueltigBis = date('d.m.Y', $row->GueltigBis);
			array_push($couponCodes, $row);
		}

		if ($num > $limit)
		{
			$page_nav = " <a class=\"pnav\" href=\"index.php?do=modules&action=modedit&mod=shop&moduleaction=couponcodes&cp=" . SESSION . "&page={s}\">{t}</a> ";
			$page_nav = get_pagination($seiten, 'page', $page_nav);
			$AVE_Template->assign('page_nav', $page_nav);
		}

		$AVE_Template->assign('randomVar', $this->randomVar());
		$AVE_Template->assign('couponCodes', $couponCodes);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_couponcodes.tpl'));
	}

	

	
	
	//=======================================================
	// Produkte anzeigen (Последние поступления)
	//=======================================================


//	function globalProductInfo($row = '') {
//		//
//	}

	//=======================================================
	// Shop - Navi erzeugen (Магазин - Навигация по категориям)
	//=======================================================


	//=======================================================
	// Shop - Navi (Магазин - Навигация)
	//=======================================================


	//=======================================================
	// Funktion zum Auslesen der Lдnder (Выборка списка стран)
	//=======================================================
	function displayCountries()
	{
		global $AVE_DB;

		$laender = array();
		$sql = $AVE_DB->Query("
			SELECT
				LandCode,
				LandName
			FROM " . PREFIX . "_countries
			WHERE Aktiv = 1
			ORDER BY Id ASC
		");
		while ($row = $sql->FetchRow()) array_push($laender,$row);

		return $laender;
	}

	//=======================================================
	// Funktion zum Auslesen der Versandkosten einer Versandart
	// (Функция расчета стоимости пересылки в зависимости от вида отправки)
	//=======================================================
	function displayShippingCost($arr = '', $vid = '')
	{
		global $AVE_DB;

		$shippingcost = array();
		$sql = $AVE_DB->Query("
			SELECT
				LandCode,
				LandName
			FROM " . PREFIX . "_countries
			WHERE Aktiv = 1
			ORDER BY LandName ASC
		");

		while ($row = $sql->FetchRow())
		{
			$vcost = array();
			if (in_array($row->LandCode,$arr))
			{
				$sql_vcost = $AVE_DB->Query("
					SELECT *
					FROM " . PREFIX . "_modul_shop_versandkosten
					WHERE Land = '" . $row->LandCode . "'
					AND VersandId = '" . $vid . "'
					ORDER BY KVon ASC
				");
				while ($row_vcost = $sql_vcost->FetchRow())
				{
					array_push($vcost, $row_vcost);
				}
				$row->versandkosten = $vcost;
				array_push($shippingcost, $row);
			}
		}

		return $shippingcost ;
	}

	//=======================================================
	// Funktion zum Auslesen der Versandarten (Выборка видов отправки)
	//=======================================================
	function displayShipper()
	{
		global $AVE_DB;

		$shipper = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_versandarten
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow()) array_push($shipper,$row);

		return $shipper;
	}

	//=======================================================
	// Funktion zum Auslesen der Gruppen (Выборка групп пользователей)
	//=======================================================
	function displayGroups()
	{
		global $AVE_DB;

		$Groups = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_user_groups
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow()) array_push($Groups,$row);

		return $Groups;
	}

	//=======================================================
	// Versandarten (Виды отправки)
	//=======================================================
	function shopShipper($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (!empty($_REQUEST['sub']))
		{
			switch ($_REQUEST['sub'])
			{
				case 'save':
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}					
				
					foreach ($_POST['Name'] as $id => $Name)
					{
						if (!empty($Name))
						{
							$AVE_DB->Query("
								UPDATE " . PREFIX . "_modul_shop_versandarten
								SET
									Name        = '" . htmlspecialchars($Name) . "',
									KeineKosten = '" . intval($_POST['KeineKosten'][$id]) . "',
									Aktiv       = '" . intval($_POST['Aktiv'][$id]) . "'
								WHERE
									Id = '" . (int)$id . "'
							");
						}
					}

					if (isset($_POST['Del']) && count($_POST['Del']) >= 1)
					{
						foreach ($_POST['Del'] as $id => $Del)
						{
							$AVE_DB->Query("
								DELETE
								FROM " . PREFIX . "_modul_shop_versandkosten
								WHERE VersandId = '" . $id . "'
							");
							$AVE_DB->Query("
								DELETE
								FROM " . PREFIX . "_modul_shop_versandarten
								WHERE Id = '" . $id . "'
							");
						}
					}
					break;

				case 'new':
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}					
					$shipper_name = trim($_POST['NewShipper']);
					if (!empty($shipper_name))
					{
						$AVE_DB->Query("
							INSERT " . PREFIX . "_modul_shop_versandarten
							SET Name = '" . htmlspecialchars($shipper_name) . "'
						");
					}
					break;
			}
		}

		$AVE_Template->assign('shopShipper',$this->displayShipper());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_shippers.tpl'));
	}

	function editShipper($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
		
			$Icon = '';
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop_versandarten
				SET
					Name              = '" . $_POST['Name'] . "',
					Beschreibung      = '" . $_POST['Beschreibung'] . "',
					Icon              = '" . $Icon . "',
					LaenderVersand    = '" . (!empty($_POST['LaenderVersand']) ? implode(',', $_POST['LaenderVersand']) : '') . "',
					Pauschalkosten    = '" . str_replace(',','.',$_POST['Pauschalkosten']) . "',
					Pauschalkosten_mn = '" . $_POST['Pauschalkosten_mn']."',
					NurBeiGewichtNull = '" . $_POST['NurBeiGewichtNull'] . "',
					ErlaubteGruppen   = '" . (!empty($_POST['ErlaubteGruppen']) ? implode(',', $_POST['ErlaubteGruppen']) : '') . "'
				WHERE
					Id = '" . $_REQUEST['Id'] . "'
			");

			echo '<script>window.opener.location.reload(); window.close();</script>';
		}

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_versandarten
			WHERE Id = '" . $_REQUEST['Id'] . "'
		");
		$row = $sql->FetchRow();
		$row->VersandLaender = explode(',', $row->LaenderVersand);
		$row->Gruppen = explode(',', $row->ErlaubteGruppen);

		$oFCKeditor = new FCKeditor('Beschreibung') ;
		$oFCKeditor->Height = '400';
		$oFCKeditor->ToolbarSet = 'cpengine_small';
		$oFCKeditor->Value = $row->Beschreibung;
		$row->Beschreibung = $oFCKeditor->Create();

		$AVE_Template->assign('laender', $this->displayCountries());
		$AVE_Template->assign('gruppen', $this->displayGroups());
		$AVE_Template->assign('ss', $row);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_shipper_edit.tpl'));
	}

	//=======================================================
	// Versandkosten bearbeiten (Стоимость пересылки)
	//=======================================================
	function editshipperCost($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		$close_window = true;
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
				if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}			
			// Einzelne lцschen
			if (isset($_POST['Del']) && count($_POST['Del']) >= 1)
			{
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_versandkosten
						WHERE Id = '" . $id . "'
					");
				}
			}

			// Neue Werte
			if (!empty($_REQUEST['NeuVon']) && !empty($_REQUEST['NeuBis']) && !empty($_REQUEST['NeuBetrag']))
			{
				$close_window = false;
				foreach ($_POST['NeuVon'] as $land => $NeuVon)
				{
					if (isset($NeuVon) && is_numeric($this->kReplace($NeuVon)) &&
						isset($_POST['NeuBis'][$land]) && is_numeric($this->kReplace($_POST['NeuBis'][$land])) &&
						isset($_POST['NeuBetrag'][$land]) && is_numeric($this->kReplace($_POST['NeuBetrag'][$land])))
					{
						$AVE_DB->Query("
							INSERT " . PREFIX . "_modul_shop_versandkosten
							SET
								VersandId = '" . $_REQUEST['Id'] . "',
								Land      = '" . $land . "',
								KVon      = '" . $this->kReplace($NeuVon) . "',
								KBis      = '" . $this->kReplace($_POST['NeuBis'][$land]) . "',
								Betrag    = '" . $this->kReplace($_POST['NeuBetrag'][$land]) . "'
						");
					}
				}
			}

			// Vorhandene Versandkosten aktualisieren
			if (isset($_POST['KVon']))
			{
				foreach ($_POST['KVon'] as $id => $KVon)
				{
					if (isset($KVon) && is_numeric($this->kReplace($KVon)) &&
						isset($_POST['KBis'][$id]) && is_numeric($this->kReplace($_POST['KBis'][$id])) &&
						isset($_POST['Betrag'][$id]) && is_numeric($this->kReplace($_POST['Betrag'][$id])))
					{
						$AVE_DB->Query("
							UPDATE " . PREFIX . "_modul_shop_versandkosten
							SET
								KVon   = '" . $this->kReplace($KVon) . "',
								KBis   = '" . $this->kReplace($_POST['KBis'][$id]) . "',
								Betrag = '" . $this->kReplace($_POST['Betrag'][$id]) . "'
							WHERE
								Id = '" . $id . "'
						");
					}
				}
			}
			if ($close_window == true) echo '<script>window.opener.location.reload(); window.close();</script>';
		}

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_versandarten
			WHERE Id = '" . $_REQUEST['Id'] . "'
		");
		$row = $sql->FetchRow();
		$row->VersandLaender = explode(',', $row->LaenderVersand);
		$AVE_Template->assign('ss', $row);

		$AVE_Template->assign('laender', $this->displayShippingCost($row->VersandLaender, $_REQUEST['Id']));
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_shipper_cost.tpl'));
	}

	//=======================================================
	// Einstellungen E-Mail (Установки E-mail)
	//=======================================================
	function emailSettings($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop
				SET
					AdresseText = '" . $_POST['AdresseText'] . "',
					AdresseHTML = '" . $_POST['AdresseHTML'] . "',
					Logo        = '" . $_POST['Logo'] . "',
					EmailFormat = '" . $_POST['EmailFormat'] . "',
					AbsEmail    = '" . chop($_POST['AbsEmail']) . "',
					AbsName     = '" . chop($_POST['AbsName']) . "',
					EmpEmail    = '" . chop($_POST['EmpEmail']) . "',
					BetreffBest = '" . $_POST['BetreffBest'] . "'
				WHERE
					Id = 1
			");
		}

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop
			LIMIT 1
		");
		$row = $sql->FetchRow();
		$row->VersandLaender = explode(',', $row->VersandLaender);

		$AVE_Template->assign('row', $row);
		$AVE_Template->assign('laender', $this->displayCountries());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_settings_email.tpl'));
	}

	//=======================================================
	// Einstellungen (Настройки)
	//=======================================================


	function settingsYML($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop
				SET
					company_name   = '" . (empty($_POST['company_name'])   ? ''  : htmlspecialchars(trim($_POST['company_name']))) . "',
					custom         = '" . (empty($_POST['custom'])         ? '0' : (int)$_POST['custom']) . "',
					delivery       = '" . (empty($_POST['delivery'])       ? '0' : (int)$_POST['delivery']) . "',
					delivery_local = '" . (empty($_POST['delivery_local']) ? '0' : (int)$_POST['delivery_local']) . "',
					downloadable   = '" . (empty($_POST['downloadable'])   ? '0' : (int)$_POST['downloadable']) . "',
					track_label    = '" . (empty($_POST['track_label'])    ? '0' : (int)$_POST['track_label']) . "'
				WHERE
					Id = '1'
			");
		}

		$shipper_times[0] = $AVE_Template->get_config_vars('YML_SelectItem');
		$sql = $AVE_DB->Query("
			SELECT
				Id,
				Name
			FROM " . PREFIX . "_modul_shop_versandzeit
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchAssocArray())
		{
			$shipper_times[$row['Id']] = $row['Name'];
		}

		$shipper_method[0] = $AVE_Template->get_config_vars('YML_SelectItem');
		$sql = $AVE_DB->Query("
			SELECT
				Id,
				Name
			FROM " . PREFIX . "_modul_shop_versandarten
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchAssocArray())
		{
			$shipper_method[$row['Id']] = $row['Name'];
		}

		$sql = $AVE_DB->Query("
			SELECT
				company_name,
				custom,
				delivery,
				delivery_local,
				downloadable,
				track_label
			FROM " . PREFIX . "_modul_shop
			LIMIT 1
		");
		$row = $sql->FetchRow();

		$AVE_Template->assign('row', $row);
		$AVE_Template->assign('shipper_times', $shipper_times);
		$AVE_Template->assign('shipper_method', $shipper_method);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_settings_yml.tpl'));
	}

	//=======================================================
	// Hilfeseiten bearbeiten (Страница помощи)
	//=======================================================
	function helpPages($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop
				SET
					VersandInfo    = '" . (!empty($_POST['VersandInfo']) ? $_POST['VersandInfo'] : '') . "',
					DatenschutzInf = '" . (!empty($_POST['DatenschutzInf']) ? $_POST['DatenschutzInf'] : '') . "',
					Impressum      = '" . (!empty($_POST['Impressum']) ? $_POST['Impressum'] : '') . "',
					ShopWillkommen = '" . (!empty($_POST['ShopWillkommen']) ? $_POST['ShopWillkommen'] : '') . "',
					ShopFuss       = '" . (!empty($_POST['ShopFuss']) ? $_POST['ShopFuss'] : '') . "',
					Agb            = '" . (!empty($_POST['Agb']) ? $_POST['Agb'] : '') . "',
					Bank1 = '" . @$_POST['Bank1'] . "',
					Bank2 = '" . @$_POST['Bank2'] . "',
					Bank3 = '" . @$_POST['Bank3'] . "',
					Bank4 = '" . @$_POST['Bank4'] . "',
					Bank5 = '" . @$_POST['Bank5'] . "',
					Bank6 = '" . @$_POST['Bank6'] . "'
				WHERE
					Id = 1
			");
		}

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop
			LIMIT 1
		");
		$row = $sql->FetchRow();

		$oFCKeditor = new FCKeditor('VersandInfo');
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Simple';
		$oFCKeditor->Value= $row->VersandInfo;
		$row->VersandInfo = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('DatenschutzInf');
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Simple';
		$oFCKeditor->Value= $row->DatenschutzInf;
		$row->DatenschutzInf = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('Impressum');
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Simple';
		$oFCKeditor->Value= $row->Impressum;
		$row->Impressum = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('ShopWillkommen');
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Simple';
		$oFCKeditor->Value= $row->ShopWillkommen;
		$row->ShopWillkommen = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('ShopFuss');
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Simple';
		$oFCKeditor->Value= $row->ShopFuss;
		$row->ShopFuss = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('Agb');
		$oFCKeditor->Height = '200';
		$oFCKeditor->ToolbarSet = 'Simple';
		$oFCKeditor->Value= $row->Agb;
		$row->Agb = $oFCKeditor->Create();

		$AVE_Template->assign('row', $row);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_settings_help_pages.tpl'));
	}

	//=======================================================
	// Versandkosten (Стоимость пересылки)
	//=======================================================

	// Versandart lцschen
	function deleteMethod($id)
	{
		global $AVE_DB, $AVE_Template;
				if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}	
		if ($id != 1 && $id != 2 && $id != 3 && $id != 4 && $id != 5)
		{
			$AVE_DB->Query("
				DELETE
				FROM " . PREFIX . "_modul_shop_zahlungsmethoden
				WHERE Id = '" . $id . "'
			");
		}

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=paymentmethods&cp=" . SESSION);
		exit;
	}

	// Versandarten auslesen
	function displayMethods()
	{
		global $AVE_DB;

		$methods = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_zahlungsmethoden
			ORDER BY Position ASC
		");
		while ($row = $sql->FetchRow()) array_push($methods,$row);

		return $methods;
	}

	// Neue Zahlungsmethode
	function newPaymentMethod()
	{
		global $AVE_DB;

		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_zahlungsmethoden
			SET Name = '" . $_POST['Name'] . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=paymentmethods&cp=" . SESSION);
		exit;
	}

	// Versandarten anzeigen & Schnellspeicherung
	function paymentMethods($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
			foreach ($_POST['Name'] as $id => $Name)
			{
				if (!empty($Name))
				{
					$AVE_DB->Query("
						UPDATE " . PREFIX . "_modul_shop_zahlungsmethoden
						SET
							Name     = '" . $Name . "',
							Aktiv    = '" . $_POST['Aktiv'][$id] . "',
							Position = '" . $_POST['Position'][$id] . "'
						WHERE
							Id = '" . $id . "'
					");
				}
			}
		}

		$AVE_Template->assign('methods', $this->displayMethods());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_payment_methods.tpl'));
	}

	// Versandart bearbeiten
	function editPaymentMethod($tpl_dir,$id)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
		
		
//			$Icon = '';
			$AVE_DB->Query("
				UPDATE " . PREFIX . "_modul_shop_zahlungsmethoden
				SET
					Name                   = '" . $_POST['Name'] . "',
					Beschreibung           = '" . $_POST['Beschreibung'] . "',
					ErlaubteVersandLaender = '" . ((isset($_POST['ErlaubteVersandLaender']) && is_array($_POST['ErlaubteVersandLaender'])) ? implode(',', $_POST['ErlaubteVersandLaender']) : '') . "',
					ErlaubteVersandarten   = '" . ((isset($_POST['ErlaubteVersandarten']) && is_array($_POST['ErlaubteVersandarten'])) ? implode(',', $_POST['ErlaubteVersandarten']) : '') . "',
					ErlaubteGruppen        = '" . ((isset($_POST['ErlaubteGruppen']) && is_array($_POST['ErlaubteGruppen'])) ? implode(',', $_POST['ErlaubteGruppen']) : '') . "',
					Aktiv                  = '" . $_POST['Aktiv'] . "',
					Kosten                 = '" . $this->kReplace($_POST['Kosten']) . "',
					KostenOperant          = '" . $_POST['KostenOperant'] . "',
					InstId                 = '" . (!empty($_POST['InstId']) ? chop($_POST['InstId']) : '') . "',
					ZahlungsBetreff        = '" . (!empty($_POST['ZahlungsBetreff']) ? $_POST['ZahlungsBetreff'] : '') . "',
					TestModus              = '" . (!empty($_POST['TestModus']) ? chop($_POST['TestModus']) : '') . "',
					Extern                 = '" . (!empty($_POST['Extern']) ? $_POST['Extern'] : '') . "',
					Gateway                = '" . (!empty($_POST['Gateway']) ? chop($_POST['Gateway']) : '') . "',
					send_time                = '" . $_POST['send_time'] . "',
					send_text                = '" . $_POST['send_text'] . "',
					order_del                = '" . $_POST['order_del'] . "',
					chat_desc                = '" . $_POST['chat_desc'] . "'
				WHERE
					Id = '" . $_REQUEST['Id'] . "'
			");

			echo '<script>window.opener.location.reload(); window.close();</script>';
		}

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_zahlungsmethoden
			WHERE Id = '" . $id . "'
		");
		$row = $sql->FetchRow();
		$row->VersandLaender = explode(',', $row->ErlaubteVersandLaender);
		$row->Gruppen = explode(',', $row->ErlaubteGruppen);
		$row->Versandarten = explode(',', $row->ErlaubteVersandarten);

		$oFCKeditor = new FCKeditor('Beschreibung') ;
		$oFCKeditor->Height = '400';
		$oFCKeditor->ToolbarSet = 'cpengine_small';
		$oFCKeditor->Value	= $row->Beschreibung;
		$Edi = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('send_text') ;
		$oFCKeditor->Height = '400';
		$oFCKeditor->ToolbarSet = 'cpengine_small';
		$oFCKeditor->Value	= $row->send_text;
		$send_text = $oFCKeditor->Create();
		
		$oFCKeditor = new FCKeditor('chat_desc') ;
		$oFCKeditor->Height = '400';
		$oFCKeditor->ToolbarSet = 'cpengine_small';
		$oFCKeditor->Value	= $row->chat_desc;
		$chat_desc = $oFCKeditor->Create();

		$AVE_Template->assign('send_text', $send_text);
		$AVE_Template->assign('chat_desc', $chat_desc);
		$AVE_Template->assign('Edi', $Edi);
		$AVE_Template->assign('laender', $this->displayCountries());
		$AVE_Template->assign('gruppen', $this->displayGroups());
		$AVE_Template->assign('shipper', $this->displayShipper());
		$AVE_Template->assign('ss', $row);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_payment_method_edit.tpl'));
	}

	//=======================================================
	// Versandzeiten (Срок доставки)
	//=======================================================
	function displaySt()
	{
		global $AVE_DB;

		$st = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_versandzeit
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow()) array_push($st,$row);

		return $st;
	}

	// Neue Versanndzeit
	function shipperTimeNew()
	{
		global $AVE_DB;

		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_versandzeit
			SET Name = '" . $_POST['Name'] . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=timeshipping&cp=" . SESSION);
		exit;
	}

	// Versandzeiten
	function shipperTime($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			if (isset($_POST['Del']) && count($_POST['Del']) >= 1)
			{
				foreach ($_POST['Del'] as $id => $Name)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_versandzeit
						WHERE Id = '" . $id . "'
					");
				}
			}

			foreach ($_POST['Name'] as $id => $Name)
			{
				if (!empty($Name))
				{
					$AVE_DB->Query("
						UPDATE " . PREFIX . "_modul_shop_versandzeit
						SET Name = '" . $Name . "'
						WHERE Id = '" . $id . "'
					");
				}
			}
		}

		$AVE_Template->assign('st', $this->displaySt());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_shipper_time.tpl'));
	}























	//=======================================================
	// Einheiten (Единицы)
	//=======================================================
	function Units($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Speichern
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			foreach ($_POST['Name'] as $id => $Name)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_einheiten
					SET
						Name        = '" . $Name . "',
						NameEinzahl = '" . $_POST['NameEinzahl'][$id] . "'
					WHERE
						Id = '" . $id . "'
				");
			}

			// Einzelne EInheit lцschen
			if (isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_einheiten
						WHERE Id = '" . $id . "'
					");
				}
			}
		}

		$Units = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_einheiten
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($Units, $row);
		}

		$AVE_Template->assign('Units', $Units);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_units.tpl'));
	}

	// Neue Einheit
	function UnitsNew()
	{
		global $AVE_DB;

		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_einheiten
			SET
				Name        = '" . $_POST['NameEinzahl'] . "',
				NameEinzahl = '" . $_POST['NameEinzahl'] . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=units&cp=" . SESSION);
		exit;
	}

	//=======================================================
	// Hersteller (Производитель)
	//=======================================================
	function Manufacturer($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Speichern
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			foreach ($_POST['Name'] as $id => $Name)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_hersteller
					SET
						Name = '" . $Name . "',
						Logo = '" . $_POST['Logo'][$id] . "',
						Link = '" . $_POST['Link'][$id] . "'
					WHERE
						Id = '" . $id . "'
				");
			}

			// Hersteller lцschen
			if (isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_hersteller
						WHERE Id = '" . $id . "'
					");
				}
			}
		}

		$Manufacturer = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_hersteller
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($Manufacturer, $row);
		}

		$AVE_Template->assign('Manufacturer', $Manufacturer);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_manufacturer.tpl'));
	}	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function usergroup($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		// Speichern
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
			foreach ($_POST['Name'] as $id => $Name)
			{
				$AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_usergroup
					SET
						Name = '" . $Name . "',
						Descr = '" . $_POST['Descr'][$id] . "'
					WHERE
						Id = '" . $id . "'
				");
			}

			// Hersteller lцschen
			if (isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach ($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_usergroup
						WHERE Id = '" . $id . "'
					");
				}
			}
		}

		$usergroup = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_usergroup
			ORDER BY Name ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($usergroup, $row);
		}

		$AVE_Template->assign('usergroup', $usergroup);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_usergroup.tpl'));
	}

	
	// Neuer Hersteller
	function usergroupNew()
	{
		global $AVE_DB;

		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_usergroup
			SET
				Name = '" . $_POST['Name'] . "',
				Descr = '" . $_POST['Descr'] . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=usergroup&cp=" . SESSION);
		exit;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	// Neuer Hersteller
	function ManufacturerNew()
	{
		global $AVE_DB;

		$AVE_DB->Query("
			INSERT " . PREFIX . "_modul_shop_hersteller
			SET
				Name = '" . $_POST['Name'] . "',
				Logo = '" . $_POST['Logo'] . "',
				Link = '" . $_POST['Link'] . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=manufacturer&cp=" . SESSION);
		exit;
	}

	//=======================================================
	// Produktvarianten zuweisen (Варианты товаров)
	//=======================================================
	function prouctVars($tpl_dir,$product_id,$kat_id,$KatId_Multi)
	{
		global $AVE_DB, $AVE_Template;

		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
		
			if (isset($_POST['NameNew']) && count($_POST['NameNew']) >= 1)
			{
			
				
				foreach ($_POST['NameNew'] as $id => $NameNew)
				{
					if (!empty($NameNew))
					{

  						$AVE_DB->Query("
							INSERT " . PREFIX . "_modul_shop_varianten
							SET
								KatId    = '" . $id . "',
								ArtId    = '" . $_REQUEST['Id'] . "',
								Name     = '" . $NameNew . "',
								Wert     = '" . $this->kReplace(chop($_REQUEST['WertNew'][$id])) . "',
								parent  = '" . $_REQUEST['parentNew'][$id] . "',
								Operant  = '" . $_REQUEST['OperantNew'][$id] . "',
								Position = '" . $_REQUEST['PositionNew'][$id] . "',
								Descr = '" . $_REQUEST['DescNew'][$id] . "',
								Lager = '" . $_REQUEST['LagerNew'][$id] . "'
						");

						
						
					}
				}
			}

			
			
			// Varianten - Kategorienamen aktualisieren
			// Varianten aktualisieren
			if (!empty($_POST['Name']))
			{
				foreach ($_POST['Name'] as $id => $Name)
				{
					$AVE_DB->Query("
						UPDATE " . PREFIX . "_modul_shop_varianten
						SET
							Name     = '" . $Name . "',
							Operant  = '" . $_POST['Operant'][$id] . "',
							Wert     = '" . $_POST['Wert'][$id] . "',
							parent     = '" . $_POST['parent'][$id] . "',
							Position = '" . $_POST['Position'][$id] . "',
							Descr = '" . $_POST['Desc'][$id] . "',
							Lager = '" . $_POST['Lager'][$id] . "',
							Rezerv = '" . $_POST['Rezerv'][$id] . "'
						WHERE
							Id = '" . $id . "'
					");
				}
			}

 			
			if (!empty($_POST['Name_Neu_2']))
			{
			
				foreach ($_POST['Name_Neu_2'] as $new2_id => $Name)
				{
					if (!empty($Name))
					{
						$new2_id = (int)$new2_id;
						$AVE_DB->Query("
							UPDATE " . PREFIX . "_modul_shop_varianten
							SET
								Name     = '" . $_POST['Name_Neu_2'][$new2_id] . "',
								Operant  = '" . $_POST['Operant_Neu_2'][$new2_id] . "',
								Wert     = '" . $_POST['Wert_Neu_2'][$new2_id] . "',
								parent     = '" . $_POST['parent_Neu_2'][$new2_id] . "',
								Position = '" . $_POST['Position_Neu_2'][$new2_id] . "',
								Descr = '" . $_POST['Desc_Neu_2'][$new2_id] . "',
								Lager = '" . $_POST['Lager_Neu_2'][$new2_id] . "',
								Rezerv = '" . $_POST['Rezerv_Neu_2'][$new2_id] . "'
							WHERE
								Id = '" . $new2_id . "'
						");
						
						
						
						
						
	 
					}
				}				
			} 
			
			
			
			
			
			
			
			
			
			
			
			// Varianten - Positionen lцschen
			if (!empty($_POST['Del']))
			{
				foreach ($_POST['Del'] as $id => $Name)
				{
					$AVE_DB->Query("
						DELETE
						FROM " . PREFIX . "_modul_shop_varianten
						WHERE Id = '" . $id . "'
					");
				}
			}
			
			header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=product_vars&cp=".SESSION."&pop=1&Id=".$product_id."&KatId=".$kat_id."&KatId_Multi=".$KatId_Multi);
			exit;
		}

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		$KatId_Multi = $AVE_DB->Query("SELECT KatId_Multi FROM " . PREFIX . "_modul_shop_product WHERE Id = '" . $product_id . "'")->FetchRow();		
		
		
		
		
		
		if(strlen($KatId_Multi->KatId_Multi) > 1)
		{
			$KatMulti = explode(',', $KatId_Multi->KatId_Multi);
				
			$dbextra = " OR KatId IN(";
			foreach($KatMulti as $value){
				$dbextra .= $value.",";
			}
			$dbextra = @substr($dbextra,0,-2);
			$dbextra .= ")";
		}
		
		
		
		$Vars = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_varianten_kategorien
			WHERE ParentId = '0' AND (KatId = '" . $kat_id . "'".$dbextra.")
			ORDER BY sort ASC, Name ASC
		");
		
		while ($row = $sql->FetchRow())
		{
		
			$SubVars = array();
			$sql_v = $AVE_DB->Query("
				SELECT *
				FROM " . PREFIX . "_modul_shop_varianten
				WHERE ArtId = '" . $product_id . "'
				AND KatId = '" . $row->Id . "'
				ORDER BY Position ASC
			");
			while ($row_v = $sql_v->FetchRow())
			{
				
				$variantCateg_2 = array();
				$sql_2 = $AVE_DB->Query("
					SELECT *
					FROM " . PREFIX . "_modul_shop_varianten_kategorien
					WHERE ParentId = '" . $row_v->KatId . "'
					ORDER BY sort ASC, Name ASC
				");
					while ($row_2 = $sql_2->fetchrow())
					{			
					
						$SubVars2 = array();
						$sql_v_2 = $AVE_DB->Query("
							SELECT *
							FROM " . PREFIX . "_modul_shop_varianten
							WHERE ArtId = '" . $product_id . "'
							AND KatId = '" . $row_v->Id . "'
							ORDER BY Position ASC
						");

						
						while ($row_v_2 = $sql_v_2->FetchRow())
						{
							//print_r($row_v_2);
							array_push($SubVars2, $row_v_2);
						}

						
						
						$row_2->SubVars2 = $SubVars2;			
					
					
						array_push($variantCateg_2, $row_2);
					}	
			
				$row_v->ebene_2 = $variantCateg_2;					
				
				
				
				
				
				array_push($SubVars, $row_v);
			}

			$row->SubVars = $SubVars;
			
			
			//print_r($row);
			array_push($Vars, $row);
		}
		$AVE_Template->assign('Vars', $Vars);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_product_vars.tpl'));
	}




















	/**
	 * Добавить новый товар
	 *
	 * @param string $tpl_dir путь к шаблонам
	 */
	function newProduct($tpl_dir)
	{
		global $AVE_DB, $AVE_Template, $config_vars;

		// Speichern
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			$DbImage = '';
			$MultiBilder = '';
			$errors = '';
			$Watermark = 'water.png';
			
			$regex = '/[^\x20-\xFF]/';
			$regex_no_space = '/[^\x21-\xFF]/';
			if (empty($_POST['ArtName']) || preg_match($regex, $_POST['ArtName']))
				$errors[] = $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductName'];
			if (empty($_POST['ArtNr']) || preg_match($regex_no_space, $_POST['ArtNr']))
				$errors[] = $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductNrS'];
			if (!empty($_POST['ArtNr']) && !$this->_checkArtNumber($_POST['ArtNr']))
				$errors[] = $GLOBALS['config_vars']['ProductNewArtnumberUnique'];
			if ($this->_getShopSetting('required_intro') && (empty($_POST['TextKurz']) || (!empty($_POST['TextKurz']) && $_POST['TextKurz'] == '<br />')))
				$errors[] = $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductTs'];
			if ($this->_getShopSetting('required_desc') && (empty($_POST['TextLang']) || (!empty($_POST['TextLang']) && $_POST['TextLang'] == '<br />')))
				$errors[] = $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductTl'];
			if ($this->_getShopSetting('required_price') && empty($_POST['Preis']) || (!empty($_POST['Preis']) && !is_numeric($_POST['Preis'])))
				$errors[] = $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductPrice'];
			if ($this->_getShopSetting('required_stock') && empty($_POST['Lager']) || (!empty($_POST['Lager']) && !is_numeric($_POST['Lager'])))
				$errors[] = $GLOBALS['config_vars']['ProductNewPCheck'] . $GLOBALS['config_vars']['ProductStored'];
			if (!empty($_FILES['Bild']['tmp_name']) && (!in_array($_FILES['Bild']['type'], $this->_allowed_images)))
				$errors[] = $GLOBALS['config_vars']['ProductNewVorbittenImage'];

			// Fehler
			if (is_array($errors))
			{
				$AVE_Template->assign('errors', $errors);
			}
			// Speichern
			else
			{
				// Bildupload
				if (!empty($_FILES['Bild']['tmp_name']))
				{
					$upload_dir = BASE_DIR . '/modules/shop/uploads/';
					$name = str_replace(array(' ', '+', '-'), '_', strtolower($_FILES['Bild']['name']));
					$name = preg_replace("/__+/", "_", $name);
//					$temp = $_FILES['Bild']['tmp_name'];
//					$endung = strtolower(substr($name, -3));
					$fupload_name = $name;

					if (in_array($_FILES['Bild']['type'], $this->_allowed_images))
					{
						// Wenn Bild existiert, Bild umbenennen
						if (file_exists($upload_dir . $fupload_name))
						{
							$fupload_name = $this->renameFile($fupload_name);
							$name = $fupload_name;
						}

						// Bild hochladen
						@move_uploaded_file($_FILES['Bild']['tmp_name'], $upload_dir . $fupload_name);
						@chmod($upload_dir . $fupload_name, 0777);
						$this->ResizeImg2($upload_dir.$fupload_name, $upload_dir.$fupload_name, 340, 340, $Watermark);

						$DbImage = $fupload_name;
					}
				}

				// Weitere Bilder
				if (isset($_FILES) && count(@$_FILES['file']['tmp_name']) >= 1 && $_FILES['file']['tmp_name'] != '')
				{
					$fupload_name = '';
					$upload_dir = BASE_DIR . '/modules/shop/uploads/';

					for ($i=0;$i<count(@$_FILES['file']['tmp_name']);$i++)
					{
//						$size = $_FILES['file']['size'][$i];
						$name = str_replace(array(' ', '+','-'),'_',strtolower($_FILES['file']['name'][$i]));
						$name = preg_replace("/__+/", "_", $name);
//						$temp = $_FILES['file']['tmp_name'][$i];
						$fupload_name = $name;

						if (file_exists($upload_dir . $fupload_name))
						{
							$fupload_name = $this->renameFile($fupload_name);
							$name = $fupload_name;
						}

						if (!empty($name) && in_array($_FILES['file']['type'][$i], $this->_allowed_images) )
						{
							@move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_dir . $fupload_name);
							@chmod($upload_dir . $fupload_name, 0777);
							$this->ResizeImg2($upload_dir.$fupload_name, $upload_dir.$fupload_name, 340, 340, $Watermark);
							$MultiBilder[] = $fupload_name;
						}
					}
				}
				// Eintrag in die DB
				$AVE_DB->Query("
					INSERT " . PREFIX . "_modul_shop_product
					SET
						ArtNr           = '" . (!empty($_POST['ArtNr']) ? chop($_POST['ArtNr']) : '') . "',
						KatId           = '" . $_POST['KatId'] . "',
						KatId_Multi     = '" . implode(',', $_POST['KatId_Multi']) . ",',
						Artname         = '" . chop($_POST['ArtName']) . "',
						Aktiv           = 1,
						Preis           = '" . $this->kReplace(chop($_POST['Preis'])) . "',
						PreisListe      = '" . $this->kReplace(chop($_POST['PreisListe'])) . "',
						Bild            = '" . $DbImage . "',
						Bild_Typ        = '" . (!empty($DbImage) ? substr($_FILES['Bild']['name'], -3) : '') . "',
						TextKurz        = '" . chop($_POST['TextKurz']) . "',
						TextLang        = '" . chop($_POST['TextLang']) . "',
						Gewicht         = '" . $this->kReplace(chop($_POST['Gewicht'])) . "',
						Angebot         = '" . $_POST['Angebot'] . "',
						Top         	= '" . $_POST['Top'] . "',
						New         	= '" . $_POST['New'] . "',
						UstZone         = '" . $_POST['UstZone'] . "',
						Erschienen      = '" . mktime(0,0,0,$_POST['ErschMonth'],$_POST['ErschDay'],$_POST['ErschYear']) . "',
						Frei_Titel_1    = '" . (!empty($_POST['Frei_Titel_1']) ? $_POST['Frei_Titel_1'] : '') . "',
						Frei_Titel_2    = '" . (!empty($_POST['Frei_Titel_2']) ? $_POST['Frei_Titel_2'] : '') . "',
						Frei_Titel_3    = '" . (!empty($_POST['Frei_Titel_3']) ? $_POST['Frei_Titel_3'] : '') . "',
						Frei_Titel_4    = '" . (!empty($_POST['Frei_Titel_4']) ? $_POST['Frei_Titel_4'] : '') . "',
						Frei_Text_1     = '" . (!empty($_POST['Frei_Text_1']) ? $_POST['Frei_Text_1'] : '') . "',
						Frei_Text_2     = '" . (!empty($_POST['Frei_Text_2']) ? $_POST['Frei_Text_2'] : '') . "',
						Frei_Text_3     = '" . (!empty($_POST['Frei_Text_3']) ? $_POST['Frei_Text_3'] : '') . "',
						Frei_Text_4     = '" . (!empty($_POST['Frei_Text_4']) ? $_POST['Frei_Text_4'] : '') . "',
						Hersteller      = '" . (!empty($_POST['Hersteller']) ? $_POST['Hersteller'] : '') . "',
						Schlagwoerter   = '" . (!empty($_POST['Schlagwoerter']) ? chop($_POST['Schlagwoerter']) : '') . "',
						Einheit         = '" . $this->kReplace(chop($_POST['Einheit'])) . "',
						EinheitId       = '" . (!empty($_POST['EinheitId']) ? $_POST['EinheitId'] : '') . "',
						Lager           = '" . chop($_POST['Lager']) . "',
						VersandZeitId   = '" . $_POST['VersandZeitId'] . "',
						DateiDownload   = '" . (!empty($_POST['DateiDownload']) ? $_POST['DateiDownload'] : '') . "',
						AngebotBild     = '" . (!empty($_POST['AngebotBild']) ? $_POST['AngebotBild'] : '') . "',
						ProdKeywords    = '" . (!empty($_POST['ProdKeywords']) ? $_POST['ProdKeywords'] : '') . "',
						ProdDescription = '" . (!empty($_POST['ProdDescription']) ? $_POST['ProdDescription'] : '') . "',
						bid             = '" . ((!empty($_POST['bid']) && is_numeric($_POST['bid'])) ? $_POST['bid'] : '0') . "',
						cbid            = '" . ((!empty($_POST['cbid']) && is_numeric($_POST['cbid'])) ? $_POST['cbid'] : '0') . "'
				");
				// ID des neuen Artikels
				$iid = $AVE_DB->InsertId();
				// Weitere Bilder speichern
				if (isset($MultiBilder) && is_array($MultiBilder) && count($MultiBilder) >= 1)
				{
					foreach ($MultiBilder as $bild)
					{
						$AVE_DB->Query("
							INSERT " . PREFIX . "_modul_shop_product_bilder
							SET
								ArtId = '" . $iid . "',
								Bild  = '" . $bild . "'
						");
					}
				}

				// Fenster schliessen...
				
$this->reportLog($_SESSION['user_name'] . ' - Добавил товар (' . stripslashes($_POST['ArtName']) . ')', 2, 2);

				echo '<script>window.opener.location.reload(); window.close();</script>';
			}
		}

		// Form anzeigen
		$oFCKeditor = new FCKeditor('TextLang'); $oFCKeditor->Height = '300'; $oFCKeditor->ToolbarSet = 'Simple'; $oFCKeditor->Value = @$_POST['TextLang']; $Lang = $oFCKeditor->Create();
		$oFCKeditor = new FCKeditor('TextKurz'); $oFCKeditor->Height = '150'; $oFCKeditor->ToolbarSet = 'Basic';  $oFCKeditor->Value = @$_POST['TextKurz']; $Kurz = $oFCKeditor->Create();

		$oFCKeditor = new FCKeditor('Frei_Text_1'); $oFCKeditor->Height = '150'; $oFCKeditor->ToolbarSet = 'Basic'; $oFCKeditor->Value = @$_POST['Frei_Text_1']; $Frei1 = $oFCKeditor->Create();
		$oFCKeditor = new FCKeditor('Frei_Text_2'); $oFCKeditor->Height = '150'; $oFCKeditor->ToolbarSet = 'Basic'; $oFCKeditor->Value = @$_POST['Frei_Text_2']; $Frei2 = $oFCKeditor->Create();
		$oFCKeditor = new FCKeditor('Frei_Text_3'); $oFCKeditor->Height = '150'; $oFCKeditor->ToolbarSet = 'Basic'; $oFCKeditor->Value = @$_POST['Frei_Text_3']; $Frei3 = $oFCKeditor->Create();
		$oFCKeditor = new FCKeditor('Frei_Text_4'); $oFCKeditor->Height = '150'; $oFCKeditor->ToolbarSet = 'Basic'; $oFCKeditor->Value = @$_POST['Frei_Text_4']; $Frei4 = $oFCKeditor->Create();

		$AVE_Template->assign('Frei1', $Frei1);
		$AVE_Template->assign('Frei2', $Frei2);
		$AVE_Template->assign('Frei3', $Frei3);
		$AVE_Template->assign('Frei4', $Frei4);

		$AVE_Template->assign('Kurz', $Kurz);
		$AVE_Template->assign('Lang', $Lang);
		$AVE_Template->assign('VatZones', $this->fetchVatZones());
		$AVE_Template->assign('Manufacturer', $this->displayManufacturer());
		$AVE_Template->assign('Units', $this->displayUnits());
		$AVE_Template->assign('ShippingTime', $this->shippingTime());
		$AVE_Template->assign('ProductCategs', $this->fetchShopNavi(1));
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_product_new.tpl'));

	}

	//=======================================================
	// Export (Экспорт)
	//=======================================================
	function dataExport($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'export')
		{
			require_once(BASE_DIR . '/modules/shop/class.export.php');

			$export = new DataExport();

			switch ($_REQUEST['t'])
			{
				case 'orders':
					$table = 'orders';
					$Prefab = 'CP_BESTELLUNGEN_';
					break;

				case 'user':
					$table = 'user';
					$Prefab = 'CP_BENUTZER_';
					break;

				case 'articles':
					$table = 'articles';
					$Prefab = 'CP_SHOPARTIKEL_';
					break;
			}

			$export->Export($Prefab . date('d_m_Y_H_i') . '',$table, @$_REQUEST['format'], @$_REQUEST['groups']);
		}

		$groups = array();
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_user_groups");
		while ($row = $sql->FetchArray())
		{
			array_push($groups, $row);
		}

		$AVE_Template->assign('ProductCategs', $this->fetchShopNavi(1));
		$AVE_Template->assign('groups', $groups);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_export_data.tpl'));
	}

	//=======================================================
	//=======================================================
	function gethost($ip)
	{
		if ($ip == '') $ip = $_SERVER['REMOTE_ADDR'];
		$longisp = @gethostbyaddr($ip);
		$isp = explode('.', $longisp);
		$isp = array_reverse($isp);
		$tmp = @$isp[1];
		if (preg_match("/\<(org?|com?|net)\>/i", $tmp))
		{
			$myisp = @$isp[2].'.'.@$isp[1].'.'.@$isp[0];
		}
		else
		{
			$myisp = @$isp[1].'.'.@$isp[0];
		}

		if (preg_match("/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $myisp)) return 'ISP lookup failed.';

		return $myisp;
	}

	//=======================================================
	// Kunden-Downloads (wie Koobi) (Загрузки клиента как в Koobi)
	//=======================================================
	function listFiles()
	{
		global $AVE_DB;

		$files = array();
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_product");

		while ($row = $sql->FetchRow())
		{
			$sql_2 = $AVE_DB->Query("
				SELECT ArtId
				FROM " . PREFIX . "_modul_shop_product_downloads
				WHERE ArtId = '" . $row->Id . "'
				LIMIT 1
			");
			$num = $sql_2->NumRows();
			if ($num == 1) array_push($files, $row);
		}

		return $files;
	}

	function shopDownloads($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (!empty($_REQUEST['sub']))
		{
			switch ($_REQUEST['sub'])
			{
				// Datei neu
				case 'new':
					$AVE_DB->Query("
						INSERT INTO " . PREFIX . "_modul_shop_downloads
						SET
							Benutzer    = '" . addslashes($_REQUEST['User']) . "',
							ArtikelId   = '" . addslashes($_REQUEST['file']) . "',
							DownloadBis = '" . mktime(23,59,59,$_REQUEST['filetimeMonth'],$_REQUEST['filetimeDay'],$_REQUEST['filetimeYear']) . "',
							Lizenz      = ''
					");
					break;


				// Aktualisieren
				case 'save':
					if (isset($_REQUEST['Id']))
					{
						foreach ($_POST['Id'] as $id=>$post)
						{
							// Speichern
							$AVE_DB->Query("
								UPDATE " . PREFIX . "_modul_shop_downloads
								SET
									Lizenz            = '" . (!empty($_POST['Lizenz'][$id]) ? $_POST['Lizenz'][$id] : '') . "',
									UrlLizenz         = '" . (!empty($_POST['UrlLizenz'][$id]) ? $_POST['UrlLizenz'][$id] : '') . "',
									DownloadBis       = '" . mktime(23,59,59,$_POST['Monat'][$id],$_POST['Tag'][$id],$_POST['Jahr'][$id]) . "',
									Gesperrt          = '" . (!empty($_POST['Gesperrt'][$id]) ? $_POST['Gesperrt'][$id] : '') . "',
									GesperrtGrund     = '" . (!empty($_POST['GesperrtGrund'][$id]) ? $_POST['GesperrtGrund'][$id] : '') . "',
									KommentarBenutzer = '" . (!empty($_POST['KommentarBenutzer'][$id]) ? addslashes($_POST['KommentarBenutzer'][$id]) : '') . "',
									KommentarAdmin    = '" . (!empty($_POST['KommentarAdmin'][$id]) ? addslashes($_POST['KommentarAdmin'][$id]) : '') . "'
								WHERE
									id = '" . $id . "'
							");
						}

						// Lцschen
						if (isset($_POST['Del']) && $_POST['Del']>=0)
						{
							foreach ($_POST['Del'] as $id => $post)
							{
								$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_downloads WHERE id = '" . $id . "'");
							}
						}
					}
					break;
			}
		}

		$Items = array();
		$sql = $AVE_DB->Query("
			SELECT
				a.*,
				b.Artname
			FROM
				" . PREFIX . "_modul_shop_downloads as a,
				" . PREFIX . "_modul_shop_product as b
			WHERE
				a.Benutzer = '" . addslashes($_REQUEST['User']) . "'
			AND
				b.ArtNr = a.ArtikelId
		");
		while ($row = $sql->FetchRow())
		{
			$row->TagEnde = date("d", $row->DownloadBis);
			$row->MonatEnde = date("m", $row->DownloadBis);
			$row->JahrEnde = date("Y", $row->DownloadBis);
			array_push($Items, $row);
		}

		$AVE_Template->assign('Start', date("Y")-6);

		$AVE_Template->assign('Items', $Items);
		$AVE_Template->assign('Files', $this->listFiles());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_customer_downloads.tpl'));
	}

	//=======================================================
	//=======================================================
	function customerDiscounts($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

/*		
		if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			foreach ($_POST['Wert'] as $key => $val)
			{
				$wert = ($val<100) ? $this->kreplace($val) : 99;
				$AVE_DB->Query("
					INSERT INTO " . PREFIX . "_modul_shop_kundenrabatte
					SET
						Wert = '" . $wert . "',
						GruppenId = '" . $key . "'
					ON DUPLICATE KEY UPDATE
						Wert = '" . $wert . "'
				");
			}
		}
*/
		
		
		
		
		
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
			foreach($_POST['Wert'] as $id => $Wert)
			{
				$s = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_modul_shop_kundenrabatte WHERE GruppenId = '$id'");
				$q = $s->numrows($s);
				if($q<1)
				{
					$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_kundenrabatte
					(
						Id,
						GruppenId,
						Wert,
						Summ,
						Summ2
					) VALUES (
						'',
						'$id',
						'" . $this->kreplace($_POST['Wert'][$id]) . "',
						'" . $this->kreplace($_POST['Summ'][$id]) . "',						
						'" . $this->kreplace($_POST['Summ2'][$id]) . "'						
					)");
				}
				
				$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_kundenrabatte SET 
					Wert = '" . (($_POST['Wert'][$id]<100) ? $this->kreplace($_POST['Wert'][$id]) : 99 ) . "',
					Summ = '".$this->kreplace($_POST['Summ'][$id])."', 					
					Summ2 = '".$this->kreplace($_POST['Summ2'][$id])."' 					
				WHERE 
					GruppenId = '$id'
					");
			}
		}
				
		
		
		$ugroups = array();
		$sql = $AVE_DB->Query("
			SELECT
				grp.*,
				kun.*,
				IFNULL(Wert,'0.00') AS Wert
			FROM " . PREFIX . "_user_groups AS grp
			LEFT JOIN " . PREFIX . "_modul_shop_kundenrabatte as kun ON GruppenId = Benutzergruppe
		");
		while ($row = $sql->FetchRow()) array_push($ugroups, $row);

		$AVE_Template->assign('Groups', $ugroups);
		$ttt = $AVE_Template->fetch($tpl_dir . 'shop_discounts.tpl');
		$AVE_Template->assign('content', $ttt);
	}

	//=======================================================
	//=======================================================
	function shopImport($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
		define("ARTICLE_IMPORT", 1);

		@require_once(BASE_DIR . "/modules/shop/class.csv.php");
		@require_once(BASE_DIR . "/modules/shop/internals/product_import.php");
	}

	//=======================================================
	//=======================================================
	function userImport($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
		define("USER_IMPORT", 1);

		@require_once(BASE_DIR . "/modules/shop/class.csv.php");
		@require_once(BASE_DIR . "/modules/shop/internals/user_import.php");
	}

	//=======================================================
	// Staffelpreise (Цены на количестве)
	//=======================================================
	function staffelPreise($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;

		if (!empty($_REQUEST['sub']))
		{
			switch ($_REQUEST['sub'])
			{
				// Nei
				case 'new':
					$AVE_DB->Query("
						INSERT " . PREFIX . "_modul_shop_staffelpreise
						SET
							StkVon = '" . (int)$_POST['Von'] . "',
							StkBis = '" . (int)$_POST['Bis'] . "',
							Preis  = '" . (!empty($_POST['Preis']) ? str_replace(',','.',$_POST['Preis']) : '') . "',
							ArtId  = '" . (int)$_REQUEST['Id'] . "'
					");
					break;

				// Aktualisieren
				case 'save':
					if (!empty($_POST['StkVon']) && is_array($_POST['StkVon']))
					{
						foreach ($_POST['StkVon'] as $id => $stk_von)
						{
							if ((is_numeric($stk_von) && $stk_von > 0) && (is_numeric($_POST['StkBis'][$id]) && $_POST['StkBis'][$id] > $stk_von))
							{
								$AVE_DB->Query("
									UPDATE " . PREFIX . "_modul_shop_staffelpreise
									SET
										StkVon = '" . (int)$stk_von . "',
										StkBis = '" . (int)$_POST['StkBis'][$id] . "',
										Preis  = '" . (!empty($_POST['Preis'][$id]) ? str_replace(',','.',$_POST['Preis'][$id]) : '') . "'
									WHERE
										Id = '" . $id . "'
								");
							}

							if (isset($_POST['Del']) && $_POST['Del']>0)
							{
								foreach ($_POST['Del'] as $id => $del)
								{
									$AVE_DB->Query("
										DELETE
										FROM " . PREFIX . "_modul_shop_staffelpreise
										WHERE Id = '" . $id . "'
									");
								}
							}
						}
					}
					break;
			}
		}

		$items = array();
		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . PREFIX . "_modul_shop_staffelpreise
			WHERE ArtId = '" . $_GET['Id'] . "'
			ORDER BY StkVon ASC
		");
		while ($row = $sql->FetchRow())
		{
			array_push($items, $row);
		}

		$AVE_Template->assign('Stf', $items);
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_product_price.tpl'));
	}

	//=======================================================
	// Fьr den Import von Benutzern aus Koobi (Импорт пользователей из Koobi)
	//=======================================================
	function dream4_userImport($Prefix = '', $Truncate = '')
	{
		global $AVE_DB;

		$sql = $AVE_DB->Query("
			SELECT *
			FROM " . $Prefix . "_user
			WHERE uid != 1
		");
		$num = $sql->NumRows();

		// Gibt es Benutzer in der alten Tabelle?
		if ($num>0)
		{
			$Truncate=1;
			if ($Truncate == 1)
			{
				$AVE_DB->Query("
					DELETE
					FROM " . PREFIX . "_modul_forum_userprofile
					WHERE BenutzerId != 1
					AND BenutzerId != '" . $_SESSION['user_id'] . "'
				");
				$AVE_DB->Query("
					DELETE
					FROM " . PREFIX . "_users
					WHERE Id != 1
					AND Id != '" . $_SESSION['user_id'] . "'
				");
				$AVE_DB->Query("
					ALTER
					TABLE " . PREFIX . "_modul_forum_userprofile
					PACK_KEYS = 0
					CHECKSUM = 0
					DELAY_KEY_WRITE = 0
					AUTO_INCREMENT = 1
				");
				$AVE_DB->Query("
					ALTER
					TABLE " . PREFIX . "_users
					PACK_KEYS = 0
					CHECKSUM = 0
					DELAY_KEY_WRITE = 0
					AUTO_INCREMENT = 1
				");
			}

			while ($row = $sql->FetchRow())
			{
				$AVE_DB->Query("
					INSERT " . PREFIX . "_modul_forum_userprofile
					SET
						BenutzerId     = '" . $row->uid . "',
						BenutzerName   = '" . $row->uname . "',
						GroupIdMisc    = '" . $row->group_id_misc . "',
						Beitraege      = '" . $row->user_posts . "',
						ZeigeProfil    = '" . $row->show_public . "',
						Signatur       = '" . $row->user_sig . "',
						Icq            = '" . $row->user_icq . "',
						Aim            = '" . $row->user_aim . "',
						Skype          = '" . $row->user_skype . "',
						Emailempfang   = '" . (($row->user_viewemail == 'yes' || $row->user_viewemail == '') ? 1 : 0) . "',
						Pnempfang      = '" . (($row->user_canpn == 'yes') ? 1 : 0) . "',
						Avatar         = '" . $row->user_avatar . "',
						AvatarStandard = '" . $row->usedefault_avatar . "',
						Webseite       = '" . $row->url . "',
						Unsichtbar     = '" . (($row->invisible == 'yes') ? 1 : 0) . "',
						Interessen     = '" . $row->user_interests . "',
						Email          = '" . $row->email . "',
						Registriert    = '" . $row->user_regdate . "',
						GeburtsTag     = '" . $row->user_birthday . "'
				");

				if ($row->uid != 2) $AVE_DB->Query("
					INSERT " . PREFIX . "_users
					SET
						Id                 = '" . $row->uid . "',
						Kennwort           = '" . $row->pass . "',
						Email              = '" . $row->email . "',
						Strasse            = '" . $row->street . "',
						HausNr             = '',
						Postleitzahl       = '" . $row->zip . "',
						city                = '" . $row->user_from . "',
						Telefon            = '" . $row->phone . "',
						Telefax            = '" . $row->fax . "',
						Bemerkungen        = '',
						Vorname            = '" . $row->name . "',
						Nachname           = '" . $row->lastname . "',
						`UserName`         = '" . $row->uname . "',
						Benutzergruppe     = '" . $row->ugroup . "',
						BenutzergruppeMisc = '" . $row->group_id_misc . "',
						Registriert        = '" . $row->user_regdate . "',
						Status             = '" . $row->status . "',
						ZuletztGesehen     = '" . $row->last_login . "',
						Land               = '" . $row->country . "',
						Geloescht          = '',
						GeloeschtDatum     = '',
						emc                = '',
						IpReg              = '',
						new_pass           = '" . $row->passtemp . "',
						Firma              = '" . $row->company . "',
						UStPflichtig       = '1',
						GebTag             = '" . $row->user_birthday . "'
				");
			}
		}
	}

	function imp()
	{
		global $AVE_DB;

		$this->dream4_userImport('kpro');

		$_REQUEST['import_from_koobi'] = 1;
		if (isset($_REQUEST['import_from_koobi']) && $_REQUEST['import_from_koobi'] == 1)
		{
			//$AVE_DB->Query("TRUNCATE TABLE " . PREFIX . "_modul_shop_product_downloads");
			$AVE_DB->Query("TRUNCATE TABLE " . PREFIX . "_modul_shop_downloads");
			$sql = $AVE_DB->Query("SELECT * FROM kpro_private_files_items");
			while ($row = $sql->FetchRow())
			{
				$sql_ts = $AVE_DB->Query("
					SELECT Id
					FROM " . PREFIX . "_modul_shop_product
					WHERE ArtNr = '" . $row->artnumber . "'
				");
				$row_ts = $sql_ts->FetchRow();

				switch ($row->type)
				{
					case '0': $ft = 'full'; break;
					case '' : $ft = 'full'; break;
					case '1': $ft = 'other'; break;
					case '2': $ft = 'bugfix'; break;
					case '3': $ft = 'update'; break;
					case '4': $ft = 'other'; break;
				}

				if (!empty($row_ts->Id))
				{
					$q = "
						INSERT
						INTO " . PREFIX . "_modul_shop_product_downloads
						SET
							ArtId        = '" . $row_ts->Id . "',
							Datei        = '" . $row->file_name . "',
							DateiTyp     = '" . $ft . "',
							Bild         = '',
							Titel        = '" . $row->file_name . "',
							Beschreibung = '" . $row->text . "',
							Position     = '1',
							Datum        = '" . $row->ctime . "'
					";
					//$AVE_DB->Query($q);
					//echo "<pre>$q</pre>";
				}
			}

			$sql = $AVE_DB->Query("SELECT * FROM kpro_private_files");
			while ($row = $sql->FetchRow())
			{
				$AVE_DB->Query("
					INSERT
					INTO " . PREFIX . "_modul_shop_downloads
					SET
						Id                = '',
						Benutzer          = '" . $row->uid . "',
						PName             = '',
						ArtikelId         = '" . $row->artnumber . "',
						DownloadBis       = '" . $row->ptilltime . "',
						Lizenz            = '" . $row->plicdata . "',
						Downloads         = '" . $row->downloads . "',
						UrlLizenz         = '" . $row->url . "',
						KommentarBenutzer = '" . $row->comment_user . "',
						KommentarAdmin    = '" . $row->comment_admin . "',
						Gesperrt          = '" . $row->locked . "',
						GesperrtGrund     = '" . $row->locked_reason . "',
						Position          = '1'
				");
			}

			$sql = $AVE_DB->Query("SELECT * FROM kpro_shop_orders");
			while ($row = $sql->FetchRow())
			{
				$row->articles = explode(',', $row->articles);
				$row->articles = serialize($row->articles);

				/*
					wait', 'progress', 'ok', 'failed', 'download')
					1 = VORK
					2 = NACHNAH
					3 = RECH
					4 = PayPal
					5 = KK
				*/

				switch ($row->payment_id)
				{
					case '1' : $payid = 1; break;
					case '2' : $payid = 2; break;
					case '3' : $payid = 5; break;
					case '5' : $payid = 4; break;
				}

				$AVE_DB->Query("
					INSERT
					INTO " . PREFIX . "_modul_shop_bestellungen
					SET
						Benutzer          = '" . $row->uid . "',
						TransId           = '" . $row->control . "',
						Datum             = '" . $row->ordertime . "',
						Gesamt            = '" . $row->ovall . "',
						USt               = '" . $row->ust . "',
						Artikel           = '" . $row->articles . "',
						Artikel_Vars      = '',
						RechnungText      = '" . $row->calculation2 . "',
						RechnungHtml      = '" . $row->calculation . "',
						NachrichtBenutzer = '" . $row->Bemerkung . "',
						Ip                = '" . $row->ip . "',
						ZahlungsId        = '" . $payid . "',
						VersandId         = '',
						KamVon            = '',
						Gutscheincode     = '" . $row->coupon_id . "',
						Bestell_Email     = '',
						Liefer_Firma      = '',
						Liefer_Abteilung  = '" . $row->shipping_company . "',
						Liefer_Vorname    = '" . $row->shipping_firstname . "',
						Liefer_Nachname   = '" . $row->shipping_lastname . "',
						Liefer_Strasse    = '" . $row->shipping_street . "',
						Liefer_Hnr        = '" . $row->shipping_streetnumber . "',
						Liefer_PLZ        = '" . $row->shipping_zip . "',
						Liefer_Ort        = '" . $row->shipping_city . "',
						Liefer_Land       = '" . $row->shipping_country . "',
						Rech_Firma        = '" . $row->rng_company . "',
						Rech_Abteilung    = '" . $row->rng_company_reciever . "',
						Rech_Vorname      = '" . $row->rng_firstname . "',
						Rech_Nachname     = '" . $row->rng_lastname . "',
						Rech_Strasse      = '" . $row->rng_street . "',
						Rech_Hnr          = '" . $row->rng_streetnumber . "',
						Rech_PLZ          = '" . $row->rng_zip . "',
						Rech_Ort          = '" . $row->rng_town . "',
						Rech_Land         = '" . $row->rng_country . "',
						Status            = '" . $row->status_o . "'
				");
			}
		}
	}
	
	
	
	
	function addcomment($tpl_dir,$id,$comment)
	{
		global $AVE_DB;
		$id = (int)$id;
		
		$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_bestellungen
			SET
				Comment = '".iconv("UTF-8", "cp1251", $this->kreplace($comment))."'
			WHERE
				Id = '$id'");
	}		
	
	
	function addidentifikator($tpl_dir,$id,$comment)
	{
		global $AVE_DB;
		$id = (int)$id;
		
		$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_bestellungen
			SET
				identifikator = '".iconv("UTF-8", "cp1251", $this->kreplace($comment))."'
			WHERE
				Id = '$id'");
	}		
	
	
	
	
	

function ResizeImg2($strSourceImagePath, $strDestImagePath, $intMaxWidth=340, $intMaxHeight=340, $water ='') {

	$water = BASE_DIR . '/modules/shop/' . $water;
	
	if($water != '' && is_file($water)) {
	
        $watermark = false;
        if (strpos(strtolower($water),".jpg") != false || strpos(strtolower($water),".jpeg") != false || strpos(strtolower($water),".jpe") != false) {
          $watermark = @imagecreatefromjpeg($water);

        } elseif (strpos(strtolower($water),".gif") != false){
          $watermark = @imagecreatefromgif($water);

        } elseif (strpos(strtolower($water),".png") != false){
          $watermark = @imagecreatefrompng($water);
        }    
  
	}
	
    $arrImageProps = getimagesize($strSourceImagePath);
    $intImgWidth   = $arrImageProps[0];
    $intImgHeight  = $arrImageProps[1];
    $intImgType    = $arrImageProps[2];
    if(!((int)$intMaxWidth > 0))
    	$intMaxWidth = 500;
    if(!((int)$intMaxHeight > 0))
    	$intMaxHeight = 500;

    switch( $intImgType) {
        case 1: $rscImg = ImageCreateFromGif($strSourceImagePath);  break;
        case 2: $rscImg = ImageCreateFromJpeg($strSourceImagePath); break;
        case 3: $rscImg = ImageCreateFromPng($strSourceImagePath);  break;
        default: return false;
    }

    if ( !$rscImg) return false;

//    if ($intImgWidth > $intImgHeight) {
//        $fltRatio = floatval($intMaxWidth / $intImgWidth);
//    } else {
//        $fltRatio = floatval($intMaxHeight / $intImgHeight);
//    }
    $WidthRatio  = floatval($intMaxWidth / $intImgWidth);
    $HeightRatio = floatval($intMaxHeight / $intImgHeight);
    $fltRatio    = min($WidthRatio,$HeightRatio);
		if ($fltRatio > 1) return true;

    $intNewWidth  = intval($fltRatio * $intImgWidth);
    $intNewHeight = intval($fltRatio * $intImgHeight);

    $rscNewImg = imagecreatetruecolor($intNewWidth, $intNewHeight);
    imagecopyresampled($rscNewImg, $rscImg, 0, 0,0, 0, $intNewWidth, $intNewHeight, $intImgWidth, $intImgHeight);
	$rscNewImg = $this->watermark($rscNewImg, $water, '');

	
    switch($intImgType) {
        case 1:  $retVal = ImageGIF($rscNewImg, $strDestImagePath);  break;
        case 3:  $retVal = ImagePNG($rscNewImg, $strDestImagePath);  break;
        case 2:  $retVal = ImageJPEG($rscNewImg, $strDestImagePath,100); break;
        default: return false;
    }

    ImageDestroy($rscNewImg);

    return true;
}	
		
	
	
	
	
	
	
	function watermark($source, $watermark, $outputType="") {
/* 	   $output = $source;
	   $logo = imagecreatefrompng($watermark);
	   
	   ImageAlphaBlending($output, true);
	   $x = ImageSX($output) - ImageSX($logo);
	   $y = ImageSY($output) - ImageSY($logo);
		
	   ImageCopy($output, $logo, $x, $y, 0, 0, ImageSX($logo), ImageSY($logo));
	   ImageDestroy($logo);
	   return $output; */
	   $output = $source;
	   $logo = imagecreatefrompng($watermark);
	   
	   ImageAlphaBlending($output, true);

	   $x_img = ImageSX($output) /2;
	   $y_img = ImageSY($output) /2;
	   
	   $x_wat = ImageSX($logo) /2;
	   $y_wat = ImageSY($logo) /2;
	   
	   $x = $x_img - $x_wat;
	   $y = $y_img - $y_wat;
	   
	   ImageCopy($output, $logo, $x, $y, 0, 0, ImageSX($logo), ImageSY($logo));
	   ImageDestroy($logo);
	   return $output;

	}	
	
	
		
	
	
	
	function get_log_payment($tpl, $order) {
	   
		global $AVE_DB;

		//print_r($order);
			
		$row = $AVE_DB->Query("SELECT PayLog FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '" . $order . "'")->FetchRow();

		//print_r($row);
		
		echo (is_object($row) ? "<pre>".$row->PayLog."</pre>" : '');
		echo '<p><strong>Fields</strong> – поля, передаваемые в форме, описаны в таблице ниже:</p><table><tr><td>Название </td><td><span class="caps">HTML</span> Field Name </td></tr><tr><td>Кошелек продавца </td><td>LMI_PAYEE_PURSE </td></tr><tr><td>Сумма платежа </td><td>LMI_PAYMENT_AMOUNT </td></tr><tr><td>Внутренний номер покупки продавца </td><td>LMI_PAYMENT_NO </td></tr><tr><td>Флаг тестового режима </td><td>LMI_MODE </td></tr><tr><td>Внутренний номер счета в системе WebMoney Transfer </td><td>LMI_SYS_INVS_NO </td></tr><tr><td>Внутренний номер платежа в системе WebMoney Transfer </td><td>LMI_SYS_TRANS_NO </td></tr><tr><td>Кошелек покупателя </td><td>LMI_PAYER_PURSE </td></tr><tr><td>WMId покупателя </td><td>LMI_PAYER_WM </td></tr><tr><td>WMId капиталлера </td><td>LMI_CAPITALLER_WMID </td></tr><tr><td>Номер ВМ-карты (электронного чека) </td><td>LMI_PAYMER_NUMBER </td></tr><tr><td>E-mail покупателя </td><td>LMI_PAYMER_EMAIL </td></tr><tr><td>Номер WM-ноты </td><td>LMI_EURONOTE_NUMBER </td></tr><tr><td>E-mail покупателя </td><td>LMI_EURONOTE_EMAIL </td></tr><tr><td>Номер телефона покупателя </td><td>LMI_TELEPAT_PHONENUMBER </td></tr><tr><td>Номер платежа в Keeper Mobile </td><td>LMI_TELEPAT_ORDERID </td></tr><tr><td>Срок кредитования </td><td>LMI_PAYMENT_CREDITDAYS </td></tr><tr><td>Внутренний номер платежа через терминалы </td><td>LMI_ATM_WMTRANSID </td></tr><tr><td>Тип платежа через терминалы </td><td>LMI_CASHIER_ATMNUMBERINSIDE </td></tr><tr><td>Контрольная подпись </td><td>LMI_HASH </td></tr><tr><td>Дата и время выполнения платежа </td><td>LMI_SYS_TRANS_DATE </td></tr><tr><td>Secret Key </td><td>LMI_SECRET_KEY </td></tr><tr><td>Примечание к платежу </td><td>LMI_PAYMENT_DESC </td></tr></table>';
		exit;
	}	
	
	
	
	
	
	
	
	function fetchZones($zone='')
	{
		global $AVE_DB;
		$Zones = array();
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_zone ORDER BY Name ASC");
		// WHERE zone='".$zone."'
		while($row = $sql->fetchrow()) array_push($Zones, $row);
		return $Zones;
	}		
	
	
	
	
	
	
	
	function Zones($tpl_dir)
	{
		global $AVE_DB, $AVE_Template;
		
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'new')
		{
			$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_zone (Id,Name,First,Follow,Avia) VALUES ('','".@$_POST[Name]."','".$this->kreplace(@$_POST['First'])."','".$this->kreplace(@$_POST['Follow'])."','".$this->kreplace(@$_POST['Avia'])."')");
		}

		
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
			foreach($_POST['Name'] as $id => $Name)
			{
				$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_zone
				SET
					First = '" . $this->kreplace($_POST['First'][$id]) . "',
					Follow = '" . $this->kreplace($_POST['Follow'][$id]) . "',
					Avia = '" . $this->kreplace($_POST['Avia'][$id]) . "',
					Name = '" . $_POST['Name'][$id] . "'
				WHERE
					Id = '$id'");
			}
			if(isset($_POST['Del']) && $_POST['Del'] >= 1)
			{
				foreach($_POST['Del'] as $id => $Del)
				{
					$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_zone WHERE Id = '$id'");
				}
			}
		}
		
		//
		$AVE_Template->assign('Zones', $this->fetchZones($_REQUEST['zone']));
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_zones.tpl'));
	}	
	
	
		//
		//
	
	
	
	function dopshipper($tpl_dir,$versandarten)
	{
		global $AVE_DB, $AVE_Template;
		
		
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'new')
		{
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
				$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_dopshipper (
					Id,
					Name,
					First,
					Follow,
					LaenderVersand,
					versandarten,
					img
				) VALUES (
					'',
					'".@$_POST[Name]."',
					'".$this->kreplace(@$_POST['First'])."',
					'".$this->kreplace(@$_POST['Follow'])."',
					'" . (!empty($_POST['LaenderVersand']) ? implode(',', $_POST['LaenderVersand']) : '') . "',
					'".$versandarten."',
					'".$_POST['img']."'
				)");
		}

		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
		{
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}			
			foreach($_POST['Name'] as $id => $Name)
			{
				if (!empty($Name))
				{	
					$LaenderVersand = $_POST['LaenderVersand'][$id];
					$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_dopshipper
					SET
						First = '" . $this->kreplace($_POST['First'][$id]) . "',
						Follow = '" . $this->kreplace($_POST['Follow'][$id]) . "',
						LaenderVersand    = '" . $LaenderVersand . "',
						Name = '" . $_POST['Name'][$id] . "',
						img = '" . $_POST['img'][$id] . "'
					WHERE
						Id = '$id'");
				}		
			}
			
			
			
			
 			foreach ($_POST['Name_Neu_2'] as $new_id => $Name)
			{
				if (!empty($Name))
				{
					$new_id = (int)$new_id;
					$LaenderVersand = $_POST['LaenderVersand_Neu_2'][$new_id];
					$AVE_DB->Query("INSERT " . PREFIX . "_modul_shop_dopshipper
						SET
						First = '" . $this->kreplace($_POST['First_Neu_2'][$new_id]) . "',
						Follow = '" . $this->kreplace($_POST['Follow_Neu_2'][$new_id]) . "',
						LaenderVersand    = '" . $LaenderVersand . "',
						Name = '" . $_POST['Name_Neu_2'][$new_id] . "',
						img = '" . $_POST['img_Neu_2'][$new_id] . "',
						versandarten = '".$versandarten."',
						ParentId = '".$new_id."'
					");
				}
				
			}			
			

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=dopshipper&cp=" . SESSION."&pop=1&versandarten=".$versandarten);
		exit;			
			
		}


		$dopshipper = array();
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_dopshipper WHERE versandarten='".$versandarten."' AND ParentId = 0 ORDER BY Name ASC");
		while($row = $sql->fetchrow()){
		
		
			$dopshipper2 = array();
			$sql_2 = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_dopshipper WHERE ParentId = '".$row->Id."' ORDER BY Name ASC");
		
    		while ($row_2 = $sql_2->fetchrow()){
				$row_2->VersandLaender = explode(',', $row_2->LaenderVersand);
				array_push($dopshipper2, $row_2);
			}
			
			
			$row->ebene_2 = $dopshipper2;		
		
		
			$row->VersandLaender = explode(',', $row->LaenderVersand);
			array_push($dopshipper, $row);
		}
		
		$AVE_Template->assign('Zones', $dopshipper);
		$AVE_Template->assign('versandarten', $versandarten);
		$AVE_Template->assign('laender', $this->displayCountries());
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_DopShipper.tpl'));
	}	
	
	
	function delete_dopshipper($id,$versandarten)
	{
		global $AVE_DB, $AVE_Template;
				if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}
		$AVE_DB->Query("
			DELETE
			FROM " . PREFIX . "_modul_shop_dopshipper
			WHERE Id = '" . $id . "'
		");

		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=dopshipper&cp=" . SESSION."&pop=1&versandarten=".$versandarten);
		exit;			
	}	
	
	
	
	
	
	
function edit_reqest($tpl_dir,$order)
{
	global $AVE_DB, $AVE_Template;
	
	$order = htmlspecialchars($order, ENT_QUOTES);

	$sql_order = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE request='".$order."'");
	$num = $sql_order->numrows();
	$row_order = $sql_order->fetchrow();

	$SystemMail = get_settings('mail_from');
	$SystemMailName = get_settings('mail_from_name');

	
	$error = '';
	$send = true;
	
		if(isset($_REQUEST['send']) && $_REQUEST['send'] == '1')
		{
	
			if(strlen(htmlspecialchars($_REQUEST['text'], ENT_QUOTES)) < 5){
				$error[] = 'Слишком короткое сообщение';
			}

		
			if(is_array($error) && count($error) > 0){
				$AVE_Template->assign('error', $error);	
				$send = false;
			}	
				
			if($send == true){
				$_REQUEST['text'] = htmlspecialchars($_REQUEST['text'], ENT_QUOTES);
				$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_request_Correspond (Id,user,request,text,time,orders,newu,newa) VALUES ('', 'admin', '".$order."', '".$_REQUEST['text']."', '".time()."', '".$row_order->Id."','1','')");
				
				//http://www.janty.ru/order_request/order='.$order.'
				$request = '<a href="http://www.janty.su/order_request/order='.$order.'"><b>ссылке</b></a>';	
				$_POST['Subject'] = "У Вас новое сообщение в заказе №".$row_order->Id." на сайте www.janty.su";
				$message = "Уважаемый (ая) <b>%%NAME%%</b>!<br /><br />Администратор сайта &quot;Janty.su&quot; изменил статус вашего заказа &nbsp;<b>%%NUMBER%%</b>&nbsp;или отправил Вам новое личное сообщение.<br /><br />Посмотреть изменения или прочитать сообщение Вы можете пройдя по %%LINK%%&nbsp;.<br/> Или воспользовавшись на сайте пунктом меню &quot;Личный кабинет&quot; - > &quot;<a href='http://www.janty.su/myorders/'>Ваши заказы</a>&quot;<br />";				
				//$this->getShopSetting('NewPostMessage');
				$message = str_replace("%%ORDER_NUMBER%%", $row_order->Id, $message);
				$message = str_replace("%%LINK%%", $request, $message);
				$message = str_replace("%%NAME%%", substr($row_order->Liefer_Vorname,0,1) . '. ' . $row_order->Liefer_Nachname, $message);
				$message = str_replace("%%NUMBER%%", "№ ".$row_order->Id, $message);
				$message = str_replace("%%SUMM%%", $row_order->Gesamt." рублей.", $message);
				$message = str_replace("%%PRICHIN%%", $row_order->pr, $message);
				
				$vowels = array("-", "(", ")", " ");
				$phone = str_replace($vowels, "", $row_order->Phone);				
				$this->send_sms("+7".$phone, $_POST['Subject']);

				
				send_mail(
					$row_order->Bestell_Email,
					$message,
					$_POST['Subject'],
					$SystemMail,
					$SystemMailName,
					'html',
					'',
					1
				);				
				
				
				
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=edit_reqest&cp=".SESSION."&pop=1&request_number=".$order);	
				exit;	
			}
			
			
			
			
		}
		
		
		
		$message = array();
		$sql = $AVE_DB->Query("SELECT * FROM ".PREFIX . "_modul_shop_request_Correspond WHERE request = '".$order."' ORDER BY time DESC");
		while($row = $sql->fetchrow())
		{
			$row->username = ($row->user == 'admin') ? 'Администратор' : substr($row_order->Liefer_Vorname,0,1) . '. ' . $row_order->Liefer_Nachname;
			$row->text = stripslashes($row->text);
			$row->date = date('d.m.Y H:i', $row->time);
			$row->newu_time = (isset($row->newu_time) && $row->newu_time) ? date("d.m.Y в H:i", $row->newu_time) : '';
			$row->timekod = $row->time;
			$row->userst = $row->user;
	
	
			if ($row->user = 'admin'){
				$row->text = str_replace("%%ORDER%%", "Ваш заказ", $row->text);
				$row->text = str_replace("%%NAME%%", substr($row_order->Liefer_Vorname,0,1) . '. ' . $row_order->Liefer_Nachname, $row->text);
				$row->text = str_replace("%%NUMBER%%", "№ ".$row_order->Id, $row->text);
				$row->text = str_replace("%%SUMM%%", $row_order->Gesamt." рублей.", $row->text);
				$row->text = str_replace("%%LINK%%", $row_order->Gesamt." рублей.", $row->text);
				$row->text = str_replace("%%PRICHIN%%", $row_order->pr, $row->text);
			}	
	
	
			array_push($message, $row);
		}
	
	
	$AVE_Template->assign('message', $message);
	$AVE_Template->assign('order', $row_order);
	$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_edit_request.tpl'));

}	
	
	
	
	
	
	
	
	
	
function read_request($id, $value)
{
	global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			//echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}		
	
	//print_r("UPDATE " . PREFIX . "_modul_shop_request_Correspond SET newa = '".$value."' WHERE id = '".$id."'");
	$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_request_Correspond SET newa = '".$value."' WHERE id = '".$id."'");		
	exit();
	
}		
	
	
	function delete_message($tpl,$order,$message)
	{
		
		global $AVE_DB, $AVE_Template;
				if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}		
		$order = htmlspecialchars($order, ENT_QUOTES);
		$message = (int)$message;
		
		$sql_order = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE request='".$order."'");
		$num = $sql_order->numrows();
		if($num < 1){
			echo '<script>window.close();</script>';
			exit;
		}
		
		$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_request_Correspond WHERE id = '$message' AND request = '$order'");
		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=edit_reqest&cp=".SESSION."&pop=1&request_number=".$order);	
		exit;	
	}		
	
	


	
	
	
	
	
	
	
	
	
	
	
	
	
function read_admin_request($id, $value)
{
	global $AVE_DB, $AVE_Template;
	

	//print_r("UPDATE " . PREFIX . "_modul_shop_request_admin SET newa = '".$value."' WHERE id = '".$id."'");
	$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_request_admin SET newa  = '".$value."', newa_time = '".time()."' WHERE id = '".$id."'");		
	exit();
	
}			
	
	
function admin_reqest($tpl_dir,$order)
{
	global $AVE_DB, $AVE_Template;
	
	$order = htmlspecialchars($order, ENT_QUOTES);

	$sql_order = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE request='".$order."'");
	$num = $sql_order->numrows();
	$row_order = $sql_order->fetchrow();

	$SystemMail = get_settings('mail_from');
	$SystemMailName = get_settings('mail_from_name');

	
	$error = '';
	$send = true;
	
		if(isset($_REQUEST['send']) && $_REQUEST['send'] == '1')
		{
	
			if(strlen(htmlspecialchars($_REQUEST['text'], ENT_QUOTES)) < 5){
				$error[] = 'ОШИБКА - Слишком короткое сообщение';
			}
			if((int)$_REQUEST['Users'] < 1){
				$error[] = 'ОШИБКА - Вы не выбрали пользователя';
			}

		
			if(is_array($error) && count($error) > 0){
				$AVE_Template->assign('error', $error);	
				$send = false;
			}	
				
			if($send == true){
				$_REQUEST['text'] = htmlspecialchars($_REQUEST['text'], ENT_QUOTES);
				//$_REQUEST['text'] = nl2br(stripslashes($_REQUEST['text']));
				$AVE_DB->Query("INSERT INTO " . PREFIX . "_modul_shop_request_admin 
				(Id,touser,createuser,text,time,orders,newu,newa) VALUES 
				('', '".(int)$_REQUEST['Users']."', '".$_SESSION['user_id']."','".$_REQUEST['text']."', '".time()."', '".$order."','','1')");
				
/* 				//http://www.janty.ru/order_request/order='.$order.'
				$request = '<a href="http://www.janty.su/order_request/order='.$order.'"><b>ссылке</b></a>';	
				$_POST['Subject'] = "У Вас новое сообщение в заказе №".$row_order->Id." на сайте www.janty.su";
				$message = "Уважаемый (ая) <b>%%NAME%%</b>!<br /><br />Администратор сайта &quot;Janty.su&quot; изменил статус вашего заказа &nbsp;<b>%%NUMBER%%</b>&nbsp;или отправил Вам новое личное сообщение.<br /><br />Посмотреть изменения или прочитать сообщение Вы можете пройдя по %%LINK%%&nbsp;.<br/> Или воспользовавшись на сайте пунктом меню &quot;Личный кабинет&quot; - > &quot;<a href='http://www.janty.su/myorders/'>Ваши заказы</a>&quot;<br />";				
				//$this->getShopSetting('NewPostMessage');
				$message = str_replace("%%ORDER_NUMBER%%", $row_order->Id, $message);
				$message = str_replace("%%LINK%%", $request, $message);
				$message = str_replace("%%NAME%%", substr($row_order->Liefer_Vorname,0,1) . '. ' . $row_order->Liefer_Nachname, $message);
				$message = str_replace("%%NUMBER%%", "№ ".$row_order->Id, $message);
				$message = str_replace("%%SUMM%%", $row_order->Gesamt." рублей.", $message);
				$message = str_replace("%%PRICHIN%%", $row_order->pr, $message);
				
				//$vowels = array("-", "(", ")", " ");
				//$phone = str_replace($vowels, "", $row_order->Phone);				
				//$this->send_sms("+7".$phone, $_POST['Subject']);
 */
				
/* 				send_mail(
					$row_order->Bestell_Email,
					$message,
					$_POST['Subject'],
					$SystemMail,
					$SystemMailName,
					'html',
					'',
					1
				); */				
				
				
				
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=admin_reqest&cp=".SESSION."&pop=1&orders=".$order);	
				exit;	
			}
			
			
			
			
		}
		
		
		
		$message = array();
		$sql = $AVE_DB->Query("SELECT * FROM ".PREFIX . "_modul_shop_request_admin WHERE orders = '".$order."' ORDER BY time DESC");
		while($row = $sql->fetchrow())
		{
			$row->createusername  = ($row->createuser   == $_SESSION['user_id']) ? 'Вас' : $this->getUserName($row->createuser );
			$row->tousername = ($row->touser  == $_SESSION['user_id']) ? 'Вам' : $this->getUserName($row->touser);
			
			
			
			
			
			
			
			$row->text = nl2br(stripslashes($row->text));
			$row->date = date('d.m.Y H:i', $row->time);
			//$row->read_date = date('d.m.Y H:i', $row->newa_time);
			$row->read_date = (isset($row->newa_time) && $row->newa_time) ? date("d.m.Y в H:i", $row->newa_time) : '';
			$row->timekod = $row->time;
			$row->userst = $row->user;
	
	
			//if ($row->user = 'admin'){
			//	$row->text = str_replace("%%ORDER%%", "Ваш заказ", $row->text);
			//	$row->text = str_replace("%%NAME%%", substr($row_order->Liefer_Vorname,0,1) . '. ' . $row_order->Liefer_Nachname, $row->text);
			//	$row->text = str_replace("%%NUMBER%%", "№ ".$row_order->Id, $row->text);
			//	$row->text = str_replace("%%SUMM%%", $row_order->Gesamt." рублей.", $row->text);
			//	$row->text = str_replace("%%LINK%%", $row_order->Gesamt." рублей.", $row->text);
			//	$row->text = str_replace("%%PRICHIN%%", $row_order->pr, $row->text);
			//}	
	
	
			array_push($message, $row);
		}
		
	$users = array();
	$sql_u = $AVE_DB->Query("SELECT Id,Vorname,Nachname,UserName FROM " . PREFIX . "_users WHERE Benutzergruppe=1 ORDER BY Nachname ASC, UserName ASC");	
	while($row_u = $sql_u->fetchrow()){array_push($users, $row_u);}
	
	
	
	
	$AVE_Template->assign('users', $users);
	$AVE_Template->assign('message', $message);
	$AVE_Template->assign('order', $row_order);
	$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_edit_request_admin.tpl'));

}		
		
function delete_admin_message($tpl,$order,$message)
{
	global $AVE_DB, $AVE_Template;
				if($_SESSION['user_group'] !=1){
				echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
				exit;
			}	
	$message = (int)$message;
	$AVE_DB->Query("DELETE FROM " . PREFIX . "_modul_shop_request_Correspond WHERE id = '".$message."' AND createuser = '".$_SESSION['user_id']."'");
	header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=admin_reqest&cp=".SESSION."&pop=1&orders=".$order);	
	exit;	
}			

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	


function parse($tpl_dir){
	global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}		
/////// сумма заказа
		$price_query = '';
		if (!empty($_REQUEST['price_start']) && !empty($_REQUEST['price_end']))
		{
			$price_query = " AND (Gesamt BETWEEN " . $this->kreplace($_REQUEST['price_start']) . " AND " . $this->kreplace($_REQUEST['price_end']) . ")";
		}


/////// регион заказа
		$region_query = '';
		if(isset($_REQUEST['LaenderVersand']) && strlen($_REQUEST['LaenderVersand']) > 1)
		{
			$region_query = " AND Liefer_Land IN(";
			foreach($_REQUEST['LaenderVersand'] as $value){
				$region_query .= $value.",";
			}
			$region_query = @substr($region_query,0,-1);
			$region_query .= ")";
		}		


/////// Статус заказа
		$status_query = '';
		if(isset($_REQUEST['Status']) && strlen($_REQUEST['Status']) > 1)
		{
			$status_query = " AND Status IN(";
			foreach($_REQUEST['Status'] as $value){
				$status_query .= "'".$value."',";
			}
			$status_query = @substr($status_query,0,-1);
			$status_query .= ")";
		}	


/////// Вариант оплаты
		$ZahlungsId_query = '';
		if(isset($_REQUEST['ZahlungsId']) && strlen($_REQUEST['ZahlungsId']) > 1)
		{
			$ZahlungsId_query = " AND ZahlungsId IN(";
			foreach($_REQUEST['ZahlungsId'] as $value){
				$ZahlungsId_query .= $value.",";
			}
			$ZahlungsId_query = @substr($ZahlungsId_query,0,-1);
			$ZahlungsId_query .= ")";
		}	

		
/////// Вариант доставки
		$VersandId_query = '';
		if(isset($_REQUEST['VersandId']) && strlen($_REQUEST['VersandId']) > 1)
		{
			$VersandId_query = " AND VersandId IN(";
			foreach($_REQUEST['VersandId'] as $value){
				$VersandId_query .= $value.",";
			}
			$VersandId_query = @substr($VersandId_query,0,-1);
			$VersandId_query .= ")";
		}	

		$ZeitStart = '';
		$ZeitEnde = '';
/*
 		if (isset($_REQUEST['start_Day']) && isset($_REQUEST['start_Hour'])){
			$ZeitStart = mktime($_REQUEST['start_Hour'],0,1,$_REQUEST['start_Month'],$_REQUEST['start_Day'],$_REQUEST['start_Year']);

		}

		if (isset($_REQUEST['end_Day']) && isset($_REQUEST['end_Hour'])){
			$ZeitEnde = mktime($_REQUEST['end_Hour'],0,1,$_REQUEST['end_Month'],$_REQUEST['end_Day'],$_REQUEST['end_Year']);

		}
		
		if (isset($ZeitStart) || isset($ZeitEnde){
			$ZeitSpanne = "AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ") ";
		} */


		
		if (isset($_REQUEST['start_Day']))
		{
			$ZeitStart = mktime(0,0,0,$_REQUEST['start_Month'],$_REQUEST['start_Day'],$_REQUEST['start_Year']);
		}
		else
		{
			$ZeitStart = (isset($_REQUEST['date']) && $_REQUEST['date'] == 'today') ? mktime(0,0,1,date("m"),date("d"),date("Y")) : mktime(0,0,1,date("m")-1,date("d"),date("Y"));
		}

		if (isset($_REQUEST['end_Day']))
		{
			$ZeitEnde = mktime(23,59,59,$_REQUEST['end_Month'],$_REQUEST['end_Day'],$_REQUEST['end_Year']);
		}
		else
		{
			$ZeitEnde = mktime(23,59,59,date("m"),date("d"),date("Y"));
		}
		
		$ZeitSpanne = (isset($_REQUEST['search']) && $_REQUEST['search'] == 1 || isset($_REQUEST['date'])) ? "AND (Datum BETWEEN " . $ZeitStart . " AND " . $ZeitEnde . ") " : "";		
		
		
		
if(isset($_REQUEST['search']) && $_REQUEST['search'] == 1)
{




		$sql = $AVE_DB->Query("
			SELECT
				*
			FROM " . PREFIX . "_modul_shop_bestellungen
			WHERE Id != 0
			" . $price_query . "
			" . $region_query . "
			" . $status_query . "
			" . $ZahlungsId_query . "
			" . $VersandId_query . "
			" . $ZeitSpanne
		);
	
		$articles = array();	
		$art = array();	
		$alltotal = '';
 		while ($row = $sql->FetchRow())
		{

			$Artikel = unserialize($row->Artikel);
			$ArtikelVars = unserialize($row->Artikel_Vars);
			
			if (is_array($Artikel))
			{
					//$count = 0;
					foreach ($Artikel as $key => $value)
					{
						$art[$key] = $art[$key]+$value;	
					}
			}
			
/* 			if (is_array($ArtikelVars))
				{
						foreach ($ArtikelVars as $keys => $values)
						{
							if ($key == $keys) $row['ArtikelS'] .= "<br />" . $this->splitVars($values);
						}
				} */	
				
		}
		ksort($art, SORT_NUMERIC);
		//print_r($art);
		//$row
 		foreach ($art as $key => $value)
		{
			$art = $this->getArticleName($key);
			$row['name'] = (is_object($art) ? ((strlen($art->ArtName)>60) ? substr($art->ArtName, 0, 60) . '...' : $art->ArtName) : '');
			$row['value'] = $value;
			$row['price'] = (is_object($art) ? number_format($art->Preis,'0',',','.') : '');
			$row['total'] = $art->Preis*$value;
			$row['total2'] = (is_object($art) ? number_format($row['total'],'0',',','.') : '');
			
			$var = @explode('_', $key);
			$row['Id'] = $var[0]; 
			unset($var[0]);
			if(count($var) < 1)unset($var);
			$row['variant'] = '';
			if (is_array($var))
			{
				foreach ($var as $keys => $values)
				{
					$row['variant'] .= $this->splitVars($values)."<br/>";
				}
			}
			$alltotal += $row['total'];
			array_push($articles, $row);
		}
	$alltotal = (is_object($art) ? number_format($alltotal,'0',',','.') : '');

//			
		
}

	//print_r($articles);



						//print_r($art[$key]."<br>");

						//$value = 1;
						//$count = $art[$key];
						
						//$value = ($value > 0) ? $value : 1;

/* 					if (is_array($ArtikelVars))
					{
						foreach ($ArtikelVars as $keys => $values)
						{
							if ($key == $keys) $row['ArtikelS'] .= "<br />" . $this->splitVars($values);
						}
					}
 */




		
		
		
		
/* 						$art = $this->getArticleName($key);
						$row->ArtikelS .= "<br />$value x <a href=javascript:void(0) onclick=cp_pop(\'index.php?do=modules&action=modedit&mod=shop&moduleaction=edit_product&cp=" . SESSION . "&pop=1&Id=" . $key . "\',\'980\',\'740\',\'1\',\'edit_product\');>" . (is_object($art) ? ((strlen($art->ArtName)>60) ? substr($art->ArtName, 0, 60) . '...' : $art->ArtName) : '') . "</a>";
						$row->Gewicht += ($art->Gewicht * $value);
 */		
		
		
		

		
		//print_r($status_query);
		//print_r($region_query);
		
/* while($row=mysql_fetch_assoc($res))
	{
	    // Cохраняем события в массиве, группируя их по годам:
	    $dates[date('Y',strtotime($row['date_event']))][] = $row;
	} */		
	
	
	
	
	
	$AVE_Template->assign('alltotal', $alltotal);
	$AVE_Template->assign('articles', $articles);
	$AVE_Template->assign('ZeitStart', $ZeitStart);
	$AVE_Template->assign('ZeitEnde', $ZeitEnde);	
	$AVE_Template->assign('laender', get_country_list(1));
	$AVE_Template->assign('usergroup', $this->displayusergroup());	
	$AVE_Template->assign('paymentMethods', $this->displayPaymentMethods());
	$AVE_Template->assign('shippingMethods', $this->displayShippingMethods());	
	
	
	if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'Экспорт в xls')
	{	
 		$export_file = "articles_order_export.xls";
		header('Pragma: public');
		header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
		header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
		header ("Pragma: no-cache");
		header("Expires: 0");
		header('Content-Transfer-Encoding: windows-1251');
		header('Content-Type: application/vnd.ms-excel;'); // This should work for IE & Opera
		header('Content-Disposition: attachment; filename="'.$export_file.'"'); 
		echo $AVE_Template->fetch($tpl_dir . 'shop_parse_orders_export.tpl');
		exit;			
	}else{
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_parse_orders.tpl'));
	}	
}
































	
	
	
	
function reportLog($meldung, $typ = 0, $rub = 0)
{
	global $AVE_DB;

	$AVE_DB->Query("
		INSERT INTO " . PREFIX . "_log
		SET
			Id		= '',
			Zeit	= '" . time() . "',
			IpCode	= '" . addslashes($_SERVER['REMOTE_ADDR']) . "',
			Seite	= '" . addslashes($_SERVER['QUERY_STRING']) . "',
			Meldung	= '" . addslashes($meldung) . "',
			LogTyp	= '" . (int)$typ . "',
			Rub		= '" . (int)$rub . "'
	");
}	
	
	
	function getUserGroup($id)
	{
		global $AVE_DB;
		$sql = $AVE_DB->Query("SELECT Benutzergruppe  FROM " . PREFIX . "_users WHERE Id = '$id'");
		@$row = $sql->fetchrow();
		return @$row->Benutzergruppe;
	}		
	
	function Get_Gutscheincode($id)
	{
		global $AVE_DB;
		$sql_k = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_gutscheine WHERE Id = '$id'");
		@$row_k = $sql_k->fetchrow();
		return @$row_k;
	}		
	
	function getDiscount($id)
	{
		global $AVE_DB;
		$sql = $AVE_DB->Query("SELECT Wert FROM " . PREFIX . "_modul_shop_kundenrabatte WHERE GruppenId = '$id' LIMIT 1");
		@$row = $sql->fetchrow();
		$sql->close();
		if(is_object(@$row))
			return @$row->Wert;
	}	
	
















	
function Getdopshipper($id='', $shipper='')
{
		global $AVE_DB;
		$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_dopshipper WHERE Id = '".$id."' AND versandarten = '".$shipper."'")->FetchRow();
		return $row;
}	








function getDiscountVal($val,$userGroup){
	global $AVE_DB;
		if(!defined($userGroup))
		{
			$row = $AVE_DB->Query("SELECT Wert FROM " . PREFIX . "_modul_shop_kundenrabatte WHERE GruppenId = '".$userGroup."' LIMIT 1")->fetchrow();
			if(is_object($row))
			{
				$prozent_wert = $row->Wert;
				$neuer_wert = $val - ($val / 100 * $prozent_wert);
				$val = $neuer_wert;
			}
		}
		return $val;
}	




function Get_Count_Name($id){
	global $AVE_DB;
	$id = (int)$id;
    $row = $AVE_DB->Query("SELECT LandName FROM " . PREFIX . "_countries WHERE LandCode='$id'")->fetchrow();
    return $row->LandName;
}	



	
	
	
function showOrder_prod($tpl_dir,$id)
{
	
	global $AVE_DB, $AVE_Template;
		if($_SESSION['user_group'] !=1){
			echo $AVE_Template->get_config_vars('MAIN_NO_PERM_MODULES');
			exit;
		}	
	if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'save')
	{

	} else {
	

		
			$row = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_bestellungen WHERE Id = '$id'")->fetcharray();
			$orderId = $row['Id'];
			
			$edit = (@$_REQUEST['edit'] == '1') ? '&edit=1' : '';
			$userGroup = $this->getUserGroup($row['Benutzer']); // группа пользователя для подсчета груповой скидки
		
		
		
			$users = array();
			$sql_u = $AVE_DB->Query("SELECT Id,Vorname,Nachname,UserName FROM " . PREFIX . "_users ORDER BY Nachname ASC, UserName ASC");	
			while($row_u = $sql_u->fetchrow()){array_push($users, $row_u);}
			$row['users'] = $users;
		
// все что связанно с заказом  = 	$_SESSION['order_new'][$orderId]		
// все что с пользователем  = 		$_SESSION['order_new'][$orderId]['user']		
		
		
				if(isset($_REQUEST['session']) && $_REQUEST['session'] == 'new')
				{
					$_SESSION['order_new'] = array();// выстраиваем сессию, зачищаем старую	
				}

		
		
					if(@$_REQUEST['edit'] != 1) // если мы не трогаем пользователя
					{				
						$_SESSION['order_new'][$orderId]['user']['Liefer_Vorname'] = @$row['Liefer_Vorname'];
						$_SESSION['order_new'][$orderId]['user']['Liefer_Nachname'] = @$row['Liefer_Nachname'];
						$_SESSION['order_new'][$orderId]['user']['Liefer_Strasse'] = @$row['Liefer_Strasse'];
						$_SESSION['order_new'][$orderId]['user']['Liefer_Hnr'] = @$row['Liefer_Hnr'];
						$_SESSION['order_new'][$orderId]['user']['Liefer_Apr'] = @$row['Liefer_Apr'];
						$_SESSION['order_new'][$orderId]['user']['Liefer_Korp'] = @$row['Liefer_Korp'];
						$_SESSION['order_new'][$orderId]['user']['Liefer_PLZ'] = @$row['Liefer_PLZ']; // индекс
						$_SESSION['order_new'][$orderId]['user']['Liefer_NAS'] = @$row['Liefer_NAS']; // населенный пункт
						$_SESSION['order_new'][$orderId]['user']['Liefer_Ort'] = @$row['Liefer_Ort']; // название города - хз - сейчас не используется.
						$_SESSION['order_new'][$orderId]['user']['Bestell_Email'] = @$row['Bestell_Email']; // мыло
						$_SESSION['order_new'][$orderId]['user']['Phone'] = @$row['Phone']; // телефон
						// не используем сейчас $_SESSION['order_new'][$orderId]['user']['Liefer_Land_Name'] = $this->Get_Count_Name($row['Liefer_Land']);
						//$_SESSION['order_new'][$orderId]['user']['userid'] = (is_numeric(@$row['Benutzer']) && @$row['Benutzer'] >0) ? @$row['Benutzer'] : 'new' ; // id пользователя
						$_SESSION['order_new'][$orderId]['user']['userid'] = @$row['Benutzer']; // id пользователя
						$_SESSION['order_new'][$orderId]['user']['Benutzergruppe'] = (is_numeric($userGroup) && $userGroup >0) ? $userGroup : '2' ; // группа пользователя
						
						// цепляем данные о доставке и оплате
						$_SESSION['order_new'][$orderId]['PaymentId'] = @$row['ZahlungsId'];
						$_SESSION['order_new'][$orderId]['ShipperId'] = @$row['VersandId'];
						$_SESSION['order_new'][$orderId]['DopShipperId'] = @$row['DopShipperId'];
						$_SESSION['order_new'][$orderId]['DopDopShipperId'] = @$row['DopDopShipperId'];


						$_SESSION['order_new'][$orderId]['Land'] = @$row['Liefer_Land']; // город пользователя
						
					}
					
					
					
// не уверен что нам это надо
				// сбрасываем все что мы намутили с пользователями в этом заказе на того который оформлял				
				if(isset($_REQUEST['resetuser'])  && $_REQUEST['resetuser'] == 1)
				{	
					header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$_REQUEST['Id']);
					exit;
				}
// не уверен что нам это надо
				
				
				
				// редактировние пользователя				
 				if(isset($_REQUEST['edituser'])  && $_REQUEST['edituser'] == 1)
				{	
				
					if(isset($_REQUEST['userid']) && is_numeric($_REQUEST['userid']))
					{
						$userid = $_REQUEST['userid'];
						$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_users WHERE Id = '$userid'");
						$row = $sql->fetchrow();
						$_SESSION['order_new'][$orderId]['user']['Liefer_Vorname'] = $row->Vorname;
						$_SESSION['order_new'][$orderId]['user']['Liefer_Nachname'] = $row->Nachname;
						$_SESSION['order_new'][$orderId]['user']['Liefer_Strasse'] = $row->Strasse;
						$_SESSION['order_new'][$orderId]['user']['Liefer_Hnr'] = $row->HausNr;
						$_SESSION['order_new'][$orderId]['user']['Liefer_Apr'] = $row->ApNr;
						$_SESSION['order_new'][$orderId]['user']['Liefer_PLZ'] = $row->Postleitzahl;
						$_SESSION['order_new'][$orderId]['user']['Liefer_NAS'] = $row->Postleitzahl_nas; // населенный пункт
						
						$_SESSION['order_new'][$orderId]['user']['Liefer_Korp'] = $row->Hauskorp; // населенный пункт
						$_SESSION['order_new'][$orderId]['user']['Liefer_Ort'] = $row->Ort;
						$_SESSION['order_new'][$orderId]['user']['Bestell_Email'] = $row->Email;
						$_SESSION['order_new'][$orderId]['user']['Phone'] = $row->Telefon;
						$_SESSION['order_new'][$orderId]['user']['Benutzergruppe'] = (is_numeric($row->Benutzergruppe) && $row->Benutzergruppe >0) ? $row->Benutzergruppe : '2' ;
						$_SESSION['order_new'][$orderId]['user']['userid'] = $row->Id;
					
/* 						$_SESSION['order_new'][$orderId]['user']['Phone2'] = '';
						$_SESSION['order_new'][$orderId]['user']['Liefer_Land'] = $row->Land;
						$_SESSION['order_new'][$orderId]['user']['Liefer_Land_Name'] = $this->Get_Count_Name($row->Land); */
/* 						unset($_SESSION['order_new'][$orderId]['PaymentId']);
						unset($_SESSION['order_new'][$orderId]['ShipperId']);
						unset($_SESSION['order_new'][$orderId]['DopShipperId']);
						unset($_SESSION['order_new'][$orderId]['DopDopShipperId']);
						unset($_SESSION['order_new'][$orderId]['ShipperName']);
						unset($_SESSION['order_new'][$orderId]['DopShipperName']);
						unset($_SESSION['order_new'][$orderId]['DopDopShipperName']);	 */					// определяем группу пользователя
						
					}elseif(isset($_REQUEST['userid']) && $_REQUEST['userid'] == 'new'){
						$_SESSION['order_new'][$orderId]['user'] ='';
						$_SESSION['order_new'][$orderId]['user']['userid'] = 'new';
						header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$orderId."&edit=1");
						exit;

					}else{				
						$_SESSION['order_new'][$orderId]['user']['Liefer_Vorname'] = stripslashes($_REQUEST['Liefer_Vorname']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Nachname'] = stripslashes($_REQUEST['Liefer_Nachname']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Strasse'] = stripslashes($_REQUEST['Liefer_Strasse']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Hnr'] = stripslashes($_REQUEST['Liefer_Hnr']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Apr'] = stripslashes($_REQUEST['Liefer_Apr']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_PLZ'] = stripslashes($_REQUEST['Liefer_PLZ']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_NAS'] = stripslashes($_REQUEST['Liefer_NAS']); // населенный пункт
						$_SESSION['order_new'][$orderId]['user']['Liefer_Korp'] = stripslashes($_REQUEST['Liefer_Korp']); // населенный пункт
						$_SESSION['order_new'][$orderId]['user']['Liefer_Ort'] = stripslashes($_REQUEST['Liefer_Ort']);
						$_SESSION['order_new'][$orderId]['user']['Bestell_Email'] = stripslashes($_REQUEST['Bestell_Email']);
						$_SESSION['order_new'][$orderId]['user']['Phone'] = stripslashes($_REQUEST['Phone']);
						$_SESSION['order_new'][$orderId]['user']['Benutzergruppe'] = (is_numeric($userGroup) && $userGroup >0) ? $userGroup : '2' ;
						//$_SESSION['order_new'][$orderId]['user']['userid'] = (is_numeric($row['Benutzer']) && $row['Benutzer'] >0) ? $row['Benutzer'] : 'new';
						//$_SESSION['order_new'][$orderId]['user']['userid'] = stripslashes($_REQUEST['Users']);
						//$_SESSION['order_new'][$orderId]['user']['userid'] = stripslashes($_REQUEST['userid']);
					}	
						
						//Если мы изменили пользователю город, значит зачищаем все что связанно с доставкой и оплатой  и берем новый город в сессию
						if(isset($_REQUEST['Liefer_Land']) && $_REQUEST['Liefer_Land'] !='0' && $_SESSION['order_new'][$orderId]['Land'] != $_REQUEST['Liefer_Land'])
						{

						
							unset($_SESSION['order_new'][$orderId]['PaymentId']);
							unset($_SESSION['order_new'][$orderId]['ShipperId']);
							unset($_SESSION['order_new'][$orderId]['DopShipperId']);
							unset($_SESSION['order_new'][$orderId]['DopDopShipperId']);
							unset($_SESSION['order_new'][$orderId]['ShipperName']);
							unset($_SESSION['order_new'][$orderId]['DopShipperName']);
							unset($_SESSION['order_new'][$orderId]['DopDopShipperName']);						
							$_SESSION['order_new'][$orderId]['Land'] = stripslashes($_REQUEST['Liefer_Land']);
						}
				// редиректим заново на страницу
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$_REQUEST['Id']."&edit=1");
				}
				

				
				
				
/* 				
				if(isset($_REQUEST['edituser'])  && $_REQUEST['edituser'] == 1)
				{	

						$_SESSION['order_new'][$orderId]['user']['Liefer_Vorname'] = stripslashes($_REQUEST['Liefer_Vorname']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Nachname'] = stripslashes($_REQUEST['Liefer_Nachname']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Strasse'] = stripslashes($_REQUEST['Liefer_Strasse']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Hnr'] = stripslashes($_REQUEST['Liefer_Hnr']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Hnr2'] = stripslashes($_REQUEST['Liefer_Hnr2']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_PLZ'] = stripslashes($_REQUEST['Liefer_PLZ']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Ort'] = stripslashes($_REQUEST['Liefer_Ort']);
						$_SESSION['order_new'][$orderId]['user']['Bestell_Email'] = stripslashes($_REQUEST['Bestell_Email']);
						$_SESSION['order_new'][$orderId]['user']['Phone'] = stripslashes($_REQUEST['Phone']);
						$_SESSION['order_new'][$orderId]['user']['Phone2'] = stripslashes($_REQUEST['Phone2']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Land'] = stripslashes($_REQUEST['Liefer_Land']);
						$_SESSION['order_new'][$orderId]['user']['Liefer_Land_Name'] = $this->Get_Count_Name(stripslashes($_REQUEST['Liefer_Land']));
						$_SESSION['order_new'][$orderId]['user']['Benutzergruppe'] = (isset($_SESSION['order_new'][$orderId]['user']['Benutzergruppe']) && is_numeric($_SESSION['order_new'][$orderId]['user']['Benutzergruppe'])) ? $_SESSION['order_new'][$orderId]['user']['Benutzergruppe'] : '2';;
						$_SESSION['order_new'][$orderId]['user']['userid'] = stripslashes($_REQUEST['Users']);
						$_SESSION['order_new'][$orderId]['ShipperId'] = '';
					}
//(isset($_SESSION['order_new'][$orderId]['user']['userid']) && is_numeric($_SESSION['order_new'][$orderId]['user']['userid'])) ? $_SESSION['order_new'][$orderId]['user']['userid'] : 
					header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod_new&cp=".SESSION."&pop=1");
					exit;
				}		 */				
					
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				


				
	
  				if(isset($_REQUEST['editshipper'])  && $_REQUEST['editshipper'] == 1)
				{	

					$_SESSION['order_new'][$orderId]['ShipperId'] = (is_numeric($_SESSION['ShipperId']) && $_SESSION['ShipperId'] >0) ? $_SESSION['ShipperId'] : '0' ;
					$_SESSION['order_new'][$orderId]['DopShipperId'] = (is_numeric($_SESSION['DopShipperId']) && $_SESSION['DopShipperId'] >0) ? $_SESSION['DopShipperId'] : '0' ;
					$_SESSION['order_new'][$orderId]['DopDopShipperId'] = (is_numeric($_SESSION['DopDopShipperId']) && $_SESSION['DopDopShipperId'] >0) ? $_SESSION['DopDopShipperId'] : '0' ;
					$_SESSION['order_new'][$orderId]['PaymentId'] = (is_numeric($_SESSION['PaymentId']) && $_SESSION['PaymentId'] >0) ? $_SESSION['PaymentId'] : '0' ;
					//$_SESSION['order_new'][$orderId]['Land'] = (is_numeric($_SESSION['Land']) && $_SESSION['Land'] >0) ? $_SESSION['Land'] : '0' ;
						
					header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$_REQUEST['Id']."&edit=1&shedit=1");
				}

 				
				

// проверка				
				//print_r($BasketSumm."<br/>");
				//print_r("PaymentId-".$_SESSION['order_new'][$orderId]['PaymentId']."<br/>");
				//print_r("ShipperId-".$_SESSION['order_new'][$orderId]['ShipperId']."<br/>");
				//print_r("Land-".$_SESSION['order_new'][$orderId]['Land']."<br/>");
				//print_r("Dop-".$_SESSION['order_new'][$orderId]['DopShipperId']."<br/>");
				//print_r("DopDop-".$_SESSION['order_new'][$orderId]['DopDopShipperId']."<br/><br/>");		
// проверка				
				
				
				
// скидки и всякая муть с ними //				
			$row['action'] = "index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod";	
			$row['Discount'] = (is_numeric($row['Benutzer']) && ($row['Benutzer']>0) && ($this->getDiscount($userGroup)>0)) ?  $this->getDiscount($userGroup) : '';	//получаем скидку группы
			$skidka = $row['Discount'];
			print_r($skidka);
			
			@$_REQUEST['discount'] = (!isset($_REQUEST['discount']) && $_SESSION['order_new'][$orderId]['discount'] != '') ? $_SESSION['order_new'][$orderId]['discount'] : $_REQUEST['discount'];
			@$_SESSION['order_new'][$orderId]['discount'] = (isset($_REQUEST['discount']) && $_REQUEST['discount'] != '') ? $_REQUEST['discount'] : $row['adm_discount'];

			$CouponCode = $row['Gutscheincode'];
			$row_cupon = $this->Get_Gutscheincode($CouponCode);
			$row['Gutscheincode'] = (is_numeric($CouponCode) && ($CouponCode>0)) ? $row_cupon->Code : '';	// проверяем есть ли купон и сколько у него скидка, получаем код
			$row['Gutscheinproc'] = (is_numeric($CouponCode) && ($CouponCode>0)) ? $row_cupon->Prozent : '';	// проверяем есть ли купон и сколько у него скидка, получаем процент скидки
// скидки и всякая муть с ними //				

			
			
		
		
		
		
		
 			if($row['Discount'] >= $row['Gutscheinproc'] && !empty($row['Discount']) && !empty($row['Gutscheinproc'])){
				$row['Gutscheinproc'] = '';
			}else if(!empty($row['Discount']) && !empty($row['Gutscheinproc']) && $row['Discount'] > 0){
				$desc = $row['Gutscheinproc'] - $row['Discount'];
				$row['Gutscheinproc'] = $desc;
			}		
		
		 
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
// товар и его варианты //			
		if(isset($_REQUEST['products']) && $_REQUEST['products'] == 'new')
		{
			$_SESSION['order_new'][$orderId]['product'] = unserialize($row['Artikel']);
			$_SESSION['order_new'][$orderId]['product_Vars'] = unserialize($row['Artikel_Vars']);
		}	
// товар и его варианты //			

		



	
	
		if(isset($_REQUEST['add_product_id']) && $_REQUEST['add_product_id'] != "" && is_numeric($_REQUEST['add_product_id']))
		{
			
			$_SESSION['order_new'][$orderId]['product'][$_REQUEST['add_product_id']] = 1; 								// колличество
		}		

	
// удаляем или обновляем колличество товаров			
		if(isset($_REQUEST['refresh']) && $_REQUEST['refresh'] == 1)
		{
			
			if(isset($_POST['del_product']) && is_array($_POST['del_product']))
			{
				foreach($_POST['del_product'] as $id => $a)
				{
					unset($_SESSION['order_new'][$orderId]['product'][$id]);
				}
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$row['Id']."#prod");
				exit;
			}
			if(isset($_POST['amount']) && is_array($_POST['amount']))
			{
				foreach($_POST['amount'] as $id => $a)
				{
					if($_POST['amount'][$id] >= 1) $_SESSION['order_new'][$orderId]['product'][$id] =  $_POST['amount'][$id];
				}
				header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$row['Id']."#prod");
				exit;
			}
		}				

		

		
		$arr = $_SESSION['order_new'][$orderId]['product'];
		$arr_var = $_SESSION['order_new'][$orderId]['product_Vars'];
			//print_r($arr_var);
			
		$korr = '';
		if(is_array($arr))
		{
				$items = array();
				foreach ($arr as $key => $value)
				{
					$art = $this->getArticleName($key);
				
/*Варианты товара*/
					if (is_array($arr_var))
					{
						foreach ($arr_var as $keys => $values)
						{
							if ($key == $keys) @$item->Vars .= $this->splitVars($values)."<br/>";
						}
					}				
/*Варианты товара*/

						//print_r($item->Vars);

				
				
						@$item->Id = $key; // айдишник товара
						@$item->ArtNr = $art->ArtNr;	// если передали артикул, то берем, в противном случае ниже подцепим из таблицы с товарами
						@$item->ArtName = $art->ArtName;	 // наименование как артикул, либо ниже подцепим из базы товаров
						//@$item->EPreis = $art->Preis;	// цена товара без скидок
						@$item->EPreis = (!empty($row['Discount']) ? ceil($art->Preis - ($art->Preis / 100 * $row['Discount'])) : $art->Preis);
						
						
						@$manuf = $this->Get_kat_name($art->KatId); // категория товара
						@$item->manuf = ($manuf) ? $manuf->category_name : ''; // название категории товара
						@$item->Anzahl = $value; // колличество
						$item->EPreisSumme = $item->EPreis * $value; // цена * количество без распродажи
						@$item->RPreisSumme = $item->EPreis * $value; // цена * количество с распродажей
						@$item->Gewicht = $art->Gewicht * $value; // вес на колличество

						
						@$PreisGesamt 	+= $item->RPreisSumme; // сумма цены без распродажи
						
						@$GewichtGesamt 	+= $item->Gewicht; // сумма веса
						
					array_push($items, $item);
					$item = '';
					$row_a = '';					
						
				}
			$cenatovarov3 = $PreisGesamt; // товары без распродажи и с распродажей
			$_SESSION['order_new'][$orderId]['Gewicht'] = @str_replace(',', '.', $GewichtGesamt); // засовываем в сессию общий вес товаров	adm_discount
			$AVE_Template->assign('Zwisumm_adm', $cenatovarov3); // цена товаров в шаблон
			if(is_array($korr)) $AVE_Template->assign('korr', '1');
		}

	
	
	
	
	
	
	
	
	
	
		$_SESSION['Shipper'] = $this->_showShipper($_SESSION['order_new'][$orderId]['Land'], $_SESSION['order_new'][$orderId]['ShipperId'], $cenatovarov3, $orderId);	

	
	
	
	
	
	
	
	
	
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'request')
		{	
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'shipping')
			{		
				$l_land = (int)$_REQUEST['l_land'];
				$_SESSION['order_new'][$orderId]['Land'] = $l_land;
				
				
				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('showShipper', $_SESSION['Shipper']);
				$AVE_Template->assign('orderId', $orderId);
				echo $AVE_Template->fetch($tpl_dir . 'shop_get_shiper.tpl');
				exit;
			}
		
		
		
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'dopshipping')
			{		
				$l_land = (int)$_REQUEST['l_land'];
				$shiper = (int)$_REQUEST['shiper'];
				$_SESSION['ShipperId'] = $shiper;
				

				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('mainshiper', $shiper);
				foreach($_SESSION['Shipper'] as $shipper)if($shipper->Id == $shiper)foreach($shipper->dop as $value)$dopshiper[] = $value;
				$AVE_Template->assign('showShipper', $dopshiper);
				$AVE_Template->assign('orderId', $orderId);
				echo $AVE_Template->fetch($tpl_dir . 'shop_get_dop_shiper.tpl');
				exit;
			}
			
			
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'dopdopshipping')
			{		
				$l_land = (int)$_REQUEST['l_land'];
				$shiper = (int)$_REQUEST['shiper'];
				$mainshiper = (int)$_REQUEST['mainshiper'];

				
				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('dopshiper', $shiper);
				$AVE_Template->assign('mainshiper', $mainshiper);
				$AVE_Template->assign('orderId', $orderId);
				foreach($_SESSION['Shipper'] as $shipper){
					foreach($shipper->dop[$shiper]->ebene_2 as $key => $value){
						$dopshiper[] = $value;
					}
				}	
				$_SESSION['DopShipperId'] = $shiper;
				$AVE_Template->assign('showShipper', $dopshiper);
				echo $AVE_Template->fetch($tpl_dir . 'shop_get_dop_shiper.tpl');
				exit;
			}			
			
			
			
			
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'payment')
			{		

				
					$l_land = (int)$_REQUEST['l_land'];
					$mainshiper = (int)$_REQUEST['mainshiper'];
					$dopshiper = (int)$_REQUEST['dopshiper'];
					$shiper = (int)$_REQUEST['shiper'];

					$err = false;
					if(isset($mainshiper) && $mainshiper !='0' && $_SESSION['ShipperId'] != $mainshiper)$_SESSION['ShipperId'] = $mainshiper;
					if(isset($mainshiper) && $mainshiper !='0' && $_SESSION['order_new'][$orderId]['ShipperId'] != $mainshiper)$_SESSION['order_new'][$orderId]['ShipperId'] = $mainshiper;
					
					if(isset($dopshiper) && $dopshiper!='0' || $_SESSION['DopShipperId'] != $dopshiper){$_SESSION['DopShipperId'] = $dopshiper;}else{$_SESSION['DopShipperId']='0';}
					if(isset($dopshiper) && $dopshiper!='0' || $_SESSION['order_new'][$orderId]['DopShipperId'] != $dopshiper){$_SESSION['order_new'][$orderId]['DopShipperId'] = $dopshiper;}else{$_SESSION['order_new'][$orderId]['DopShipperId']='0';}
					
					if(isset($shiper) && $shiper !='0' || $_SESSION['DopDopShipperId'] != $shiper){$_SESSION['DopDopShipperId'] = $shiper;}else{$_SESSION['DopDopShipperId']='0';}
					if(isset($shiper) && $shiper !='0' || $_SESSION['order_new'][$orderId]['DopDopShipperId'] != $shiper){$_SESSION['order_new'][$orderId]['DopDopShipperId'] = $shiper;}else{$_SESSION['order_new'][$orderId]['DopDopShipperId']='0';}

					
					
					
					
					$Payment = $this->_showPaymentMethods($orderId,$mainshiper,$l_land);
					$AVE_Template->assign('l_land', $l_land);
					$AVE_Template->assign('shiper', $shiper);
					$AVE_Template->assign('PaymentMethods', $Payment);
					$AVE_Template->assign('orderId', $orderId);
					echo $AVE_Template->fetch($tpl_dir . 'shop_get_payment.tpl');
					exit;
				
			}		
			
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'button')
			{	

					$_SESSION['PaymentId'] = (int)$_REQUEST['payment'];
					echo "<input type=\"hidden\" name=\"zusammenfassung\" id=\"zus\" value=\"\" /><input onclick=\"document.getElementById('zus').value='1'\" class=\"absmiddle\" type=\"image\" src=\"/templates/ave/modules/shop/sendorder.gif\" />	";
					exit;
				
			}		
		
		
		}		
	
	
	
	
	
	
	
//PaymentText	
	
	
	
	
	
	
	
	
	
	
	
		
		
		
		
		
/* 	
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'request')
		{	
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'shipping')
			{		
				$l_land = (int)$_REQUEST['l_land'];
				$_SESSION['Shipper'] = $this->_showShipper($l_land);
				
				$_SESSION['Land'] = $l_land;
				$_POST['Land'] = $l_land;
				$_SESSION['billing_town'] = $l_land;
				$_POST['billing_town'] = $l_land;

				if (isset($_REQUEST['del']) && $_REQUEST['del'] != 'no')
				{
					unset($_SESSION['DopShipperId']);
					unset($_SESSION['ShipperId']);
					unset($_SESSION['PaymentId']);
				}	
				
				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('showShipper', $_SESSION['Shipper']);
				echo $AVE_Template->fetch($GLOBALS['mod']['tpl_dir'] . 'shop_get_shiper.tpl');
				exit;
			}	
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'dopshipping')
			{		
				$l_land = (int)$_REQUEST['l_land'];
				$shiper = (int)$_REQUEST['shiper'];
				$_SESSION['ShipperId'] = $shiper;
				$_POST['ShipperId'] = $shiper;
				
				if (isset($_REQUEST['del']) && $_REQUEST['del'] != 'no')
				{
					unset($_SESSION['PaymentId']);
				}
				
				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('mainshiper', $shiper);
				
				foreach($_SESSION['Shipper'] as $shipper)if($shipper->Id == $shiper)foreach($shipper->dop as $value)$dopshiper[] = $value;
				$AVE_Template->assign('showShipper', $dopshiper);
				echo $AVE_Template->fetch($GLOBALS['mod']['tpl_dir'] . 'shop_get_dop_shiper.tpl');
				exit;
			}
			
			
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'dopdopshipping')
			{		
				$l_land = (int)$_REQUEST['l_land'];
				$shiper = (int)$_REQUEST['shiper'];
				$mainshiper = (int)$_REQUEST['mainshiper'];
				if (isset($_REQUEST['del']) && $_REQUEST['del'] != 'no')
				{
					unset($_SESSION['PaymentId']);
				}	
				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('dopshiper', $shiper);
				$AVE_Template->assign('mainshiper', $mainshiper);
				foreach($_SESSION['Shipper'] as $shipper){
					foreach($shipper->dop[$shiper]->ebene_2 as $key => $value){
						$dopshiper[] = $value;
					}
				}	
				$_SESSION['DopShipperId'] = $shiper;
				$AVE_Template->assign('showShipper', $dopshiper);
				echo $AVE_Template->fetch($GLOBALS['mod']['tpl_dir'] . 'shop_get_dop_shiper.tpl');
				exit;
			}			
			
			
			
			
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'payment')
			{		
				if (isset($_REQUEST['del']) && $_REQUEST['del'] != 'no')
				{
					unset($_SESSION['PaymentId']);
				}	
				$l_land = (int)$_REQUEST['l_land'];
				$mainshiper = (int)$_REQUEST['mainshiper'];
				$dopshiper = (int)$_REQUEST['dopshiper'];
				$shiper = (int)$_REQUEST['shiper'];
				
				$err = false;
				if(!isset($l_land) || (isset($l_land) != $_SESSION['Land']))	$err = true;
				if($err === true){unset($_SESSION['Land']);unset($_SESSION['ShipperId']);unset($_SESSION['DopShipperId']);unset($_SESSION['DopDopShipperId']);exit;}
				if(isset($mainshiper) && $mainshiper !='0' && $_SESSION['ShipperId'] != $mainshiper)$_SESSION['ShipperId'] = $mainshiper;
				if(isset($dopshiper) && $dopshiper!='0' || $_SESSION['DopShipperId'] != $dopshiper){$_SESSION['DopShipperId'] = $dopshiper;}else{ $_SESSION['DopShipperId']='0';}
				if(isset($shiper) && $shiper !='0' || $_SESSION['DopDopShipperId'] != $shiper){$_SESSION['DopDopShipperId'] = $shiper;}else{$_SESSION['DopDopShipperId']='0';}
				
				
				
				$Payment = $this->_showPaymentMethods();
				$AVE_Template->assign('l_land', $l_land);
				$AVE_Template->assign('shiper', $shiper);
				$AVE_Template->assign('PaymentMethods', $Payment);
				echo $AVE_Template->fetch($GLOBALS['mod']['tpl_dir'] . 'shop_get_payment.tpl');
				exit;
			}		
			
			
			if(isset($_REQUEST['get']) && $_REQUEST['get'] == 'button')
			{		
				$_SESSION['PaymentId'] = (int)$_REQUEST['payment'];
				echo "<input type=\"hidden\" name=\"zusammenfassung\" id=\"zus\" value=\"\" /><input onclick=\"document.getElementById('zus').value='1'\" class=\"absmiddle\" type=\"image\" src=\"/templates/ave/modules/shop/sendorder.gif\" />	";
				exit;
			}		
		
		
		}	 */	
		
		
		
		
		
		
		
		
		
		
		
		
		
		


	
			if(isset($_SESSION['order_new'][$orderId]['Land']) && $_SESSION['order_new'][$orderId]['Land'] != '' && ($cenatovarov3 > '0'))
			{
			
			
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

				$showShipper = $this->_showShipper($_SESSION['order_new'][$orderId]['user']['Liefer_Land'], $_SESSION['order_new'][$orderId]['ShipperId'], $cenatovarov3, $orderId);
				$AVE_Template->assign('showShipper', $showShipper);
				$_SESSION['IsShipper'] = '1'; 

 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
 	

//print_r($_SESSION['Shipper']);

 				if(isset($_SESSION['Shipper']))
				{
					
					foreach($_SESSION['Shipper'] as $key => $value)
					{
						if($value->Id == $_SESSION['order_new'][$orderId]['ShipperId'])
						{
							if(!empty($_SESSION['order_new'][$orderId]['ShipperId']) && $_SESSION['order_new'][$orderId]['ShipperId'] !='0' && empty($_SESSION['order_new'][$orderId]['DopShipperId']) && empty($_SESSION['order_new'][$orderId]['DopDopShipperId']))
							{
								//print_r($value);
								$_SESSION['order_new'][$orderId]['ShipperName'] = $value->Name; // name shipper
								unset($_SESSION['order_new'][$orderId]['DopShipperName']);
								unset($_SESSION['order_new'][$orderId]['DopDopShipperName']);
								//$data_dopshiper = $this->Getdopshipper($_SESSION['order_new'][$orderId]['DopShipperId'], $_SESSION['order_new'][$orderId]['ShipperId']);
								//$value->cost = $data_dopshiper->First;
							}
							elseif(!empty($_SESSION['order_new'][$orderId]['ShipperId']) && $_SESSION['order_new'][$orderId]['ShipperId'] !='0' && !empty($_SESSION['order_new'][$orderId]['DopShipperId']) && empty($_SESSION['order_new'][$orderId]['DopDopShipperId']))
							{
								//print_r(this2);
								$_SESSION['order_new'][$orderId]['ShipperName'] = $value->Name;
								$data_dopshiper = $this->Getdopshipper($_SESSION['order_new'][$orderId]['DopShipperId'], $_SESSION['order_new'][$orderId]['ShipperId']);
								$value->cost = $data_dopshiper->First;
								$_SESSION['order_new'][$orderId]['DopShipperName'] = $data_dopshiper->Name;
								unset($_SESSION['order_new'][$orderId]['DopDopShipperName']);
							}
							elseif(!empty($_SESSION['order_new'][$orderId]['ShipperId']) && $_SESSION['order_new'][$orderId]['ShipperId'] !='0' && !empty($_SESSION['order_new'][$orderId]['DopShipperId']) && !empty($_SESSION['order_new'][$orderId]['DopDopShipperId']))
							{
								//print_r(this3);
								$_SESSION['order_new'][$orderId]['ShipperName'] = $value->Name;
								$data_dopshiper = $this->Getdopshipper($_SESSION['order_new'][$orderId]['DopDopShipperId'], $_SESSION['order_new'][$orderId]['ShipperId']);
								$value->cost = $data_dopshiper->First;
								$_SESSION['order_new'][$orderId]['DopDopShipperName'] = $data_dopshiper->Name;
								
								$data_dopshiper2 = $this->Getdopshipper($_SESSION['order_new'][$orderId]['DopShipperId'], $_SESSION['order_new'][$orderId]['ShipperId']);
								$_SESSION['order_new'][$orderId]['DopShipperName'] = $data_dopshiper2->Name;
							
								
							}

//print_r($dostavka);							
							//@$_SESSION['ShippingSumm'] = $value->cost;
							//@$_SESSION['BasketSumm'] += $value->cost;
							$dostavka = $value->cost;
							//print_r( $value->cost);
							//@$_SESSION['ShippingSummOut'] = @$_SESSION['ShippingSumm'];									
	
				
						}
					}
				}



			$AVE_Template->assign('ShipperId_Summ', $dostavka);	// стоимость доставки исходя уже из веса		
			}	
				


				

				
				
/* 				
			if(!isset($_POST['PaymentId']) && !isset($_SESSION['order_new'][$orderId]['PaymentId'])){
				$_SESSION['order_new'][$orderId]['PaymentId'] = $row['ZahlungsId'];
			}

			if (!isset($_POST['PaymentId']) && isset($_SESSION['order_new'][$orderId]['PaymentId']))
			{
				$_POST['PaymentId'][0] = $_SESSION['order_new'][$orderId]['PaymentId'];
			}
			
 */
			
			
			
			
				$adm_discount = '0';
				if($_SESSION['order_new'][$orderId]['discount'] > 0)
				{
					$adm_discount = ceil($cenatovarov3 / 100 * $_SESSION['order_new'][$orderId]['discount']);
					$row['adm_discount'] = $adm_discount;
					$row['adm_discount_cif'] = $_SESSION['order_new'][$orderId]['discount'];
				}	
				
					
				$Coupon = '0';
				if($row['Gutscheinproc'] > 0)
				{				
					if($row['Gutscheinproc'] > 0)
					{
						$Coupon = ceil($PreisGesamt / 100 * $row['Gutscheinproc']);
						$row['Gutscheinproc_sum'] = $Coupon;
					}
				}
				
				
				
				
			$SUMM = $cenatovarov3 - @$descount_sum - @$Coupon - @$adm_discount + @$dostavka;
			
			
			if (!empty($_SESSION['order_new'][$orderId]['PaymentId']))
			{
				//$_SESSION['order_new'][$orderId]['PaymentId'] = (is_array($_POST['PaymentId'])) ? $_POST['PaymentId'][0] : $_POST['PaymentId'];

				$row_pay = $AVE_DB->Query("SELECT Kosten, KostenOperant FROM " . PREFIX . "_modul_shop_zahlungsmethoden WHERE Id = '" . $_SESSION['order_new'][$orderId]['PaymentId'] . "'")->FetchRow();

				$PluMin = substr($row_pay->Kosten, 0, 1);
				
				switch ($PluMin)
				{
					case '-':
						$row_pay->Kosten = str_replace('-', '', $row_pay->Kosten);
						$Kosten = ($row_pay->KostenOperant == '%') ? $SUMM-$SUMM/100*$row_pay->Kosten : $SUMM - $row_pay->Kosten;
						
						$Kosten2 = ($row_pay->KostenOperant == '%') ? $SUMM/100*$row_pay->Kosten: $row_pay->Kosten;
						
						$KostenZahlungOp = ($row_pay->KostenOperant == '%') ? '%': $this->_getShopSetting('WaehrungSymbol');
						$_SESSION['order_new'][$orderId]['KostenZahlung'] = '- ' . $row_pay->Kosten . ' ' . $KostenZahlungOp;
						$_SESSION['order_new'][$orderId]['KostenZahlungOut'] = ($row_pay->KostenOperant == '%') ? $row_pay->Kosten: $row_pay->Kosten;
						$_SESSION['order_new'][$orderId]['KostenZahlungPM'] = '-';
						break;

					case '':
					case '+':
					default:
						$row_pay->Kosten = str_replace('+', '', $row_pay->Kosten);
						$Kosten = ($row_pay->KostenOperant == '%') ? $SUMM+$SUMM/100*$row_pay->Kosten: $SUMM + $row_pay->Kosten;
						
						$Kosten2 = ($row_pay->KostenOperant == '%') ? $SUMM/100*$row_pay->Kosten: $row_pay->Kosten;
						
						$KostenZahlungOp = ($row_pay->KostenOperant == '%') ? '%': $this->_getShopSetting('WaehrungSymbol');
						$_SESSION['order_new'][$orderId]['KostenZahlung'] = $row_pay->Kosten . ' ' . $KostenZahlungOp;
						$_SESSION['order_new'][$orderId]['KostenZahlungOut'] = ($row_pay->KostenOperant == '%') ? $row_pay->Kosten: $row_pay->Kosten;
						$_SESSION['order_new'][$orderId]['KostenZahlungPM'] = '+';
						break;
				}
				//$cenatovarov3 = $Kosten;
				$SUMM_oplata = $Kosten2;
				//print_r($SUMM_oplata);
				$_SESSION['order_new'][$orderId]['KostenZahlungSymbol'] = $KostenZahlungOp;
				//unset($_POST['PaymentId']);
			}
						









			
				
					


			
			
				
			

				
//			$AVE_Template->assign('PaymentMethods', $this->showPaymentMethods('', $orderId));
			
			
			
			
			$row['Zahlart'] = $this->ZahlungsArt($_SESSION['order_new'][$orderId]['PaymentId']);	//название оплаты
			
			//print_r($row['Zahlart']);
			
			$row['VersandArt'] = $_SESSION['order_new'][$orderId]['ShipperName'];
			
//$dostavka
//$oplata
//cenatovarov3
//KostenZahlungOut
			
//$cenatovarov3 - @$descount_sum - @$Coupon - @$adm_discount+ @$dostavka			
			
			$BasketSumm = $cenatovarov3 - @$descount_sum - @$Coupon - @$adm_discount + @$dostavka + @$SUMM_oplata;	// из стоимости товаров вычитаем заданную админом скидку и купон
			
	//print_r($BasketSumm);
		
		
				//print_r("PaymentId-".$_SESSION['order_new'][$orderId]['PaymentId']."<br/>");
				//print_r("ShipperId-".$_SESSION['order_new'][$orderId]['ShipperId']."<br/>");
				//print_r("Land-".$_SESSION['order_new'][$orderId]['Land']."<br/>");
				//print_r("Dop-".$_SESSION['order_new'][$orderId]['DopShipperId']."<br/>");
				//print_r("DopDop-".$_SESSION['order_new'][$orderId]['DopDopShipperId']."<br/>");		
		
		
		
		
		
			$AVE_Template->assign('BasketSumm', $BasketSumm);	
			
			$razn = ($BasketSumm > $row['Gesamt'] || $BasketSumm < $row['Gesamt']) ? $BasketSumm - $row['Gesamt'] : '';
			
			$AVE_Template->assign('razn', $razn);					
				
				
				
			$_SESSION['order_new'][$orderId]['BasketSumm'] = $BasketSumm;
			$_SESSION['order_new'][$orderId]['Nad_Dost'] = @$SUMM_oplata + @$dostavka;
			//$_SESSION['order_new'][$orderId]['benefit'] = $benefit;
			$_SESSION['order_new'][$orderId]['NachrichtAdmin'] = nl2br(stripslashes($_POST['NachrichtAdmin']));
			
			
			//$AVE_Template->assign('benefit', $benefit); // отправим нашу прибыль в шаблон				
			$AVE_Template->assign('GewichtSumm_adm', str_replace(',','.',$GewichtGesamt));
			$AVE_Template->assign('available_countries', get_country_list(1));
			$AVE_Template->assign('Items', $items);			
			$AVE_Template->assign('Currency', 'руб.');			
			$AVE_Template->assign('row', $row);
	
			$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_edit_order_edit_prod_new.tpl'));
			
		}


//////////////////////////////////////////////////////////		
		if(isset($_REQUEST['send'])  && $_REQUEST['send'] == 1)
		{
		
				$ProductsOrder = (isset($_SESSION['order_new'][$orderId]['product']) && $_SESSION['order_new'][$orderId]['product'] != '') ? serialize($_SESSION['order_new'][$orderId]['product']) : '';
				$transId = '' . $this->_transId('7') . '' . date('dmy');
				$USt = '';
				$RechnungText = '';
				$RechnungHtml = '';
		
		
				if(!@$row['Id'] && !@$row['TransId']){
				

				
					$q = "INSERT INTO " . PREFIX ."_modul_shop_bestellungen (
							Id,
							Benutzer,
							TransId,
							Datum,
							Gesamt,
							costs,
							USt,
							Artikel,
							RechnungHtml,
							ZahlungsId,
							VersandId,
							DopShipperId,
							DopDopShipperId,
							Bestell_Email,
							Liefer_Vorname,
							Liefer_Nachname,
							Liefer_Strasse,
							Liefer_Hnr,
							Liefer_Apr,
							Liefer_Korp,
							Liefer_PLZ,
							Liefer_Land,
							Liefer_Ort,
							Liefer_NAS,
							Phone,
							Status,
							NachrichtAdmin,
							adm_discount
						) VALUES (
							'',
							'" . $_SESSION['order_new'][$orderId]['user']['userid']."',
							'" . $transId."',
							'" . time() . "',
							'" . $BasketSumm . "',
							'" . $_SESSION['order_new'][$orderId]['Nad_Dost']. "',
							'0.00',
							'" . $ProductsOrder. "',
							'" . $RechnungHtml . "',
							'" . $_SESSION['order_new'][$orderId]['PaymentId'] . "',
							'" . $_SESSION['order_new'][$orderId]['ShipperId'] . "',
							'" . $_SESSION['order_new'][$orderId]['DopShipperId'] . "',
							'" . $_SESSION['order_new'][$orderId]['DopDopShipperId'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Bestell_Email'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Vorname'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Nachname'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Strasse'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Hnr']. "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Apr']."',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Korp']."',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_PLZ'] . "',
							'" . $_SESSION['order_new'][$orderId]['Land'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_Ort'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Liefer_NAS'] . "',
							'" . $_SESSION['order_new'][$orderId]['user']['Phone'] . "',
							'wait',
							'" . $_REQUEST['NachrichtAdmin'] . "',
							'" . $_SESSION['order_new'][$orderId]['discount'] . "'
						)
					";

					$sql = $AVE_DB->Query($q);
					$OrderId = $AVE_DB->insertid();
					$AVE_Template->assign('OrderId', $OrderId);
					$AVE_Template->assign('transId', $transId);
				
				}else{
				
					$Artikel = unserialize($row['Artikel']);
					if (is_array($Artikel))
					{
						foreach ($Artikel as $key => $value)
						{
							$AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_product SET Rezerv = Rezerv-" . $value . " WHERE Id = '" . $key . "'");
						}
					}	
				
 					$sql = $AVE_DB->Query("
					UPDATE " . PREFIX . "_modul_shop_bestellungen 
					SET 
						Gesamt = '".$BasketSumm."',
						costs = '".$_SESSION['order_new'][$orderId]['Nad_Dost']."',
						Artikel = '".$ProductsOrder."',
						RechnungText = '".$RechnungText."',
						RechnungHtml = '".$RechnungHtml."',
						NachrichtAdmin = '".$_SESSION['order_new'][$orderId]['NachrichtAdmin']."',
						adm_discount = '".stripslashes($_SESSION['order_new'][$orderId]['discount'])."',
						VersandId = '".$_SESSION['order_new'][$orderId]['ShipperId']."',
						DopShipperId = '".$_SESSION['order_new'][$orderId]['DopShipperId']."',
						DopDopShipperId = '".$_SESSION['order_new'][$orderId]['DopDopShipperId']."',
						ZahlungsId = '".$_SESSION['order_new'][$orderId]['PaymentId']."',
						Bestell_Email = '".$_SESSION['order_new'][$orderId]['user']['Bestell_Email']."',
						Liefer_Vorname = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Vorname']."',
						Liefer_Nachname = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Nachname']."',
						Liefer_Strasse = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Strasse']."',
						Liefer_Hnr = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Hnr']."',
						Liefer_Apr = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Apr']."',
						Liefer_Korp = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Korp']."',
						Liefer_PLZ = '".$_SESSION['order_new'][$orderId]['user']['Liefer_PLZ']."',
						Liefer_Land = '".$_SESSION['order_new'][$orderId]['Land']."',
						Liefer_NAS = '".$_SESSION['order_new'][$orderId]['user']['Liefer_NAS']."',
						Liefer_Ort = '".$_SESSION['order_new'][$orderId]['user']['Liefer_Ort']."',
						Phone = '".$_SESSION['order_new'][$orderId]['user']['Phone']."',
						Benutzer = '".$_SESSION['order_new'][$orderId]['user']['userid']."'
					WHERE Id='".$row['Id']."' AND TransId = '".$row['TransId']."'
					"); 

					$OrderId = $row['Id'];
				}

				
				
					$arr = $_SESSION['order_new'][$orderId]['product'];// обновляем товары - сколько раз покупали
					
					foreach ($arr as $key => $value)
					{
						$sql = $AVE_DB->Query("UPDATE " . PREFIX . "_modul_shop_product SET Bestellungen=Bestellungen+".$value.", Rezerv = Rezerv+".$value ." WHERE Id='".$key."'");
					}

						//$AVE_Template->assign('PaymentText', ($this->getShopSetting('EmailFormat') == 'html' ? $this->getPaymentText($row['ZahlungsId']) : strip_tags($this->getPaymentText($row['ZahlungsId']))));
						$AVE_Template->assign('PaymentText', ($this->_getShopSetting('EmailFormat') == 'html' ? $this->_getPaymentText($_SESSION['order_new'][$orderId]['PaymentId']) : strip_tags($this->_getPaymentText($_SESSION['order_new'][$orderId]['PaymentId']))));
						$AVE_Template->assign('NachrichtAdmin', nl2br(stripslashes($_POST['NachrichtAdmin'])));
						$AVE_Template->assign('OrderTime', time());

		
						$mail_html = $AVE_Template->fetch($tpl_dir . 'shop_orderconfirm_html.tpl'); // генерирум счет
//print_r($mail_html);
						//$globals = new Globals;
						
 					if($_POST['SendMail'] == '1')// отправляем мыло
					{
						$SystemMail = get_settings("mail_from");
						$SystemMailName = get_settings("mail_from_name");
						send_mail($_SESSION['order_new'][$orderId]['user']['Bestell_Email'],$mail_html,"Изменение данных заказа на сайте Janty.su",$SystemMail,$SystemMailName,"html",'',1);	
						send_mail($SystemMail,$mail_html,"Изменение данных заказа на сайте Janty.su",$SystemMail,$SystemMailName,"html",'',1);							
						$AVE_Template->assign('innerhtml', htmlspecialchars($mail_html));
						$AVE_Template->assign('ok', '1');//пользователю и админу
					}else{
						$AVE_Template->assign('ok', '2');
					}

			
	
					// обновляем заказ - вносим туда сгенерированный счет
					$sql = $AVE_DB->Query("UPDATE " . PREFIX ."_modul_shop_bestellungen SET RechnungHtml = '$mail_html' WHERE Id = '".$OrderId."'");

										
										
										
				echo '<script>window.opener.location.reload();window.close();</script>';
				//RechnungText = '$mail_text'
				//header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=showOrder_prod&cp=".SESSION."&pop=1&Id=".$row['Id']."&session=new&products=new");	
				//exit;
				
				
			
		}					//print_r($_SESSION['order_new']);

	}	
	
	


function _showPaymentMethods($orderId,$ShipperId,$Land)
{
		global $AVE_DB;

		// unset($_SESSION['PaymentId']);
		$PaymentMethods = array();
		if (isset($_SESSION['order_new'][$orderId]['ShipperId']) && isset($_SESSION['order_new'][$orderId]['Land']) )
		{
			$sql = $AVE_DB->Query("
				SELECT *
				FROM " . PREFIX . "_modul_shop_zahlungsmethoden
				WHERE Aktiv = 1
				ORDER BY Position ASC
			");
			while ($row = $sql->FetchRow())
			{
				$Laender = explode(',', $row->ErlaubteVersandLaender);
				$Gruppen = explode(',', $row->ErlaubteGruppen);
				$Versand = explode(',', $row->ErlaubteVersandarten);
				$row->Kosten = $row->Kosten;

				// Nur Zahlungsarten fьr erlaubte Benutzergruppe ausgeben
				if (in_array($ShipperId, $Versand) && in_array($Land,$Laender)) array_push($PaymentMethods, $row);
			}
		}

		return $PaymentMethods;
}



/* 
	function showPaymentMethods($gruppen='', $orderId){
		global $AVE_DB;
		$PaymentMethods = array();
		if(isset($_SESSION['order_new'][$orderId]['ShipperId']) && isset($_SESSION['order_new'][$orderId]['user']['Liefer_Land']) )
		{
			$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_zahlungsmethoden WHERE Aktiv = 1 ORDER BY Position ASC");
			while($row = $sql->fetchrow())
			{
				$Laender = explode(',', $row->ErlaubteVersandLaender);
				$Gruppen = explode(',', $row->ErlaubteGruppen);
				$Versand = explode(',', $row->ErlaubteVersandarten);
				$row->Kosten = $row->Kosten;

				if(in_array($_SESSION['order_new'][$orderId]['ShipperId'], $Versand) && in_array($_SESSION['order_new'][$orderId]['user']['Liefer_Land'],$Laender) && in_array($_SESSION['order_new'][$orderId]['user']['Benutzergruppe'], $Gruppen)) array_push($PaymentMethods, $row);

			}
		}
		//print_r($PaymentMethods);
		return $PaymentMethods;
	} */



function Get_kat_name($id){
	global $AVE_DB;
	$id = (int)$id;
    $cat = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_category WHERE Id = '$id'")->fetchrow();
return $cat;
}




/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

function _showShipper($land = '', $ShipperId = '', $summ = '', $orderid)
{
		global $AVE_DB, $AVE_Template;

		$shipper = array();
		$si_count = 0;
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_versandarten WHERE Aktiv = 1");
		
		while ($row = $sql->FetchRow())
		{
			$row->L = explode(',', $row->LaenderVersand);
			if ($row->NurBeiGewichtNull == 1 && $_SESSION['order_new'][$orderid]['Gewicht'] > '0.00')
			{
				// Versabdart anzeigen, die nur fьr Downloads gedacht sind!
			}
			else
			{
				if (in_array($land,$row->L))
				{
				
					if ($row->Id=='2')
					{	
					
						$row_z = $AVE_DB->Query("SELECT * FROM ".PREFIX."_modul_shop_zone WHERE Id = (SELECT Zone FROM ".PREFIX."_countries WHERE LandCode = '".$land."')")->fetchrow();
							if (is_object($row_z))
							{
								$row_z->Avia = ($row->Id=='9') ? $row_z->Avia : '0';
								$kg = ceil($_SESSION['order_new'][$orderid]['Gewicht'] / '0.5');
								
								$row->cost = ($kg >= 1) ? ($row_z->First + (($kg - 1) * $row_z->Follow)) + $row_z->Avia : $row_z->First + $row_z->Avia;
								
								if ($row->Pauschalkosten>0 && ($row->Pauschalkosten_mn=='pr' || $row->Pauschalkosten_mn=='kt'))
								{ 
									$row->cost = ($row->Pauschalkosten_mn=='pr') ? ($row->cost + (($summ / 100) * $row->Pauschalkosten)) : $row->cost + $row->Pauschalkosten;
								}								
								
								$row->cost = ceil($row->cost);
								
							}
					}else{
				
				
				
						$dbex = ($row->KeineKosten == 1) ? '' : 'AND (' . $_SESSION['order_new'][$orderid]['Gewicht'] . ' BETWEEN KVon AND KBis)';

						if ($row->KeineKosten == 0 && $row->Pauschalkosten < 1)
						{
							$row->cost = '0.00';//print_r($row);
						}
						else if ($row->Pauschalkosten>0)
						{
							$row->cost = $row->Pauschalkosten;
							$row->is_pauschal = 1;
						}
						else
						{
							$sql_cost = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_versandkosten WHERE VersandId = '" . $row->Id . "'" . $dbex . " AND Land = '" . $land . "' LIMIT 1");
							$row_cost = $sql_cost->FetchRow();
							$row->cost = (is_object($row_cost)) ? $row_cost->Betrag : '';
						}

					}
					
					
					
					
					@$row->Groups = @explode(',', $row->ErlaubteGruppen);
					if (@$row->cost && in_array($_SESSION['user_group'], $row->Groups)) array_push($shipper, $row);
					if (@$row->cost) $si_count++;
				}
			}
		}
		$sql->Close();
		$AVE_Template->assign('si_count', $si_count);

		return $shipper;
	}
 */

	
	
	









































	
	
	
	
	
	function Get_dop_shipper($id, $land)
	{
		global $AVE_DB;
		
		if (isset($id) && isset($land))
		{
			$DopShipper = array();
			$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_dopshipper WHERE versandarten='".$id."' AND LaenderVersand='".$land."' AND ParentId = 0 ORDER BY Id ASC");
			while($row = $sql->fetchrow()){
			//
			
				//$row->ebene_2 = array();
				$sql_2 = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_dopshipper WHERE versandarten='".$id."' AND LaenderVersand='".$land."' AND ParentId = '".$row->Id."' ORDER BY Id ASC");
				
				//$row->price = array()
				while ($row_2 = $sql_2->fetchrow()){
				
					$row_2->VersandLaender = explode(',', $row_2->LaenderVersand);
					
					$row->price[] = $row_2->First;
					//print_r($row->price);
					
					$row->ebene_2[$row_2->Id] = $row_2;
				}
				$row->minprice  = @min($row->price); 
				$row->maxprice  = @max($row->price); 
				//$row->ebene_2 = (count($dopshipper2) > 0) ? $dopshipper2 : "";
				
		
		
				$DopShipper[$row->Id] = $row;
				//array_push($DopShipper, $row);
				

				
			}
		}
		
 if($_SESSION['user_group'] == 1)
{		
		
		
			//print_r($DopShipper);
			
}	 	
		
		
		return $DopShipper;
	}		
	
	
	
	
	
	
	function _showShipper($land = '', $ShipperId = '', $summ = '', $orderid)
	{
		global $AVE_DB, $AVE_Template;

		$shipper = array();
		$si_count = 0;
		$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_shop_versandarten WHERE Aktiv = 1");
		
		
		
		
		
		while ($row = $sql->FetchRow())
		{
		
			$row->L = explode(',', $row->LaenderVersand);
			if ($row->NurBeiGewichtNull == 1 && $_SESSION['order_new'][$orderid]['Gewicht'] > '0.00')
			{
				// Versabdart anzeigen, die nur fьr Downloads gedacht sind!
			}
			else
			{
						
				if (in_array($land,$row->L))
				{
				

				
					$row->dop = $this->Get_dop_shipper($row->Id, $land);
					$row->dop_ok = (count($row->dop) > 0) ? true : false;
				
				
					if ($row->Id=='2')
					{	
					
						$row_z = $AVE_DB->Query("SELECT * FROM ".PREFIX."_modul_shop_zone WHERE Id = (SELECT Zone FROM ".PREFIX."_countries WHERE LandCode = '".$land."')")->fetchrow();
							if (is_object($row_z))
							{
								$row_z->Avia = ($row->Id=='9') ? $row_z->Avia : '0';
								$kg = ceil($_SESSION['order_new'][$orderid]['Gewicht'] / '0.5');
								
								$row->cost = ($kg >= 1) ? ($row_z->First + (($kg - 1) * $row_z->Follow)) + $row_z->Avia : $row_z->First + $row_z->Avia;
								
								if ($row->Pauschalkosten>0 && ($row->Pauschalkosten_mn=='pr' || $row->Pauschalkosten_mn=='kt'))
								{ 
									$row->cost = ($row->Pauschalkosten_mn=='pr') ? ($row->cost + (($summ / 100) * $row->Pauschalkosten)) : $row->cost + $row->Pauschalkosten;
								}								
								
								$row->cost = ceil($row->cost);
								
							}
					
					
					}
					
					if ($row->Id=='6')
					{	
					
			
				
						$row_r = $AVE_DB->Query("SELECT * FROM ".PREFIX."_countries WHERE LandCode = '".$land."'")->fetchrow();
						$to = $row_r->code;
						
						if (isset($to) && strlen($to) > 5)
						{
							$geocode = file_get_contents("http://emspost.ru/api/rest?method=ems.calculate&from=city--sankt-peterburg&to=".$to."&weight=".$_SESSION['order_new'][$orderid]['Gewicht']."");
							$output = json_decode($geocode);
							
							if($output->rsp->stat == 'ok'){
							
								$row->cost = $output->rsp->price;
								$row->dopName = "<small style='text-transform: lowercase; font-weight:normal;font-size:10px;'>(срок доставки составит: ".$output->rsp->term->min." - ".$output->rsp->term->max." дн.)<br/>Страховка отправления включена в стоимость</small>";
								
								if ($row->Pauschalkosten>0 && ($row->Pauschalkosten_mn=='pr' || $row->Pauschalkosten_mn=='kt'))
								{ 
									$row->cost = ($row->Pauschalkosten_mn=='pr') ? ($row->cost + (($summ / 100) * $row->Pauschalkosten)) : $row->cost + $row->Pauschalkosten;
								}		
							
							
							}
							
						}else{
						
						$row->cost = "Ошибка";
						$row->dopName = "<small style='text-transform: lowercase; font-weight:normal;font-size:10px;'>Возникла ошибка при формировании запроса стоимости доставки, попробуйте еще раз, в случае повторения ошибки, пожалуйста сообщите администратору сайта</small>";
						reportLog("Ошибка - EMS - строка запроса: http://emspost.ru/api/rest?method=ems.calculate&from=city--sankt-peterburg&to=".$to."&weight=".$_SESSION['order_new'][$orderid]['Gewicht'].", город: ".$land."", 2, 2);
						
						}

					
					
					
					
					}
					if($row->Id!='6' && $row->Id!='2')
					{
				
				
				
						$dbex = ($row->KeineKosten == 1) ? '' : 'AND (' . $_SESSION['order_new'][$orderid]['Gewicht'] . ' BETWEEN KVon AND KBis)';

						if ($row->KeineKosten == 0 && $row->Pauschalkosten < 1)
						{
							$row->cost = '0.00';//print_r($row);
						}
						else if ($row->Pauschalkosten>0)
						{
							$row->cost = $row->Pauschalkosten;
							$row->is_pauschal = 1;
						}
						else
						{
							$sql_cost = $AVE_DB->Query("
								SELECT *
								FROM " . PREFIX . "_modul_shop_versandkosten
								WHERE VersandId = '" . $row->Id . "'
								" . $dbex . "
								AND Land = '" . $land . "'
								LIMIT 1
							");
							$row_cost = $sql_cost->FetchRow();
							$row->cost = (is_object($row_cost)) ? $row_cost->Betrag : '';
						}

					}
					
					print_r($_SESSION['order_new'][$orderId]['user']['Benutzergruppe']);
					
					//@$row->Groups = @explode(',', $row->ErlaubteGruppen);
					array_push($shipper, $row);
					if (@$row->cost) $si_count++;
				}
			}
		}

		
		
		$sql->Close();
		$AVE_Template->assign('si_count', $si_count);

		return $shipper;
	}	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function _shipperSumm($land = '', $Id = '', $orderid)
	{
		global $AVE_DB;

		
		if ($Id=='2')
		{
		
			$row_z = $AVE_DB->Query("SELECT * FROM ".PREFIX."_modul_shop_zone WHERE Id = (SELECT Zone FROM ".PREFIX."_countries WHERE LandCode = '".$land."')")->fetchrow();
				if (is_object($row_z))
				{
					$row_z->Avia = ($Id=='9') ? $row_z->Avia : '0';
					$kg = ceil($_SESSION['order_new'][$orderid]['Gewicht'] / '0.5');
					$Betrag = ($kg >= 1) ? ($row_z->First + (($kg - 1) * $row_z->Follow)) + $row_z->Avia : $row_z->First + $row_z->Avia;								
					$Betrag = ceil($Betrag);
				}		
		
		
		}else{
			$Betrag = $AVE_DB->Query("SELECT Betrag FROM " . PREFIX . "_modul_shop_versandkosten WHERE Land = '" . $land . "' AND VersandId = '" . $Id . "' AND (" . $_SESSION['order_new'][$orderid]['Gewicht'] . " BETWEEN KVon AND KBis) LIMIT 1")->GetCell();
		}
		
		
		
		
		return @$Betrag;
	}


	function _transId($c = 0)
	{
		$transid = '';
		$chars = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
			'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',
			'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',
			'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z');
		$ch = ($c != 0) ? $c : 7;
		$count = count($chars) - 1;
		srand((double)microtime() * 1000000);
		for ($i = 0; $i < $ch; $i++)
		{
			$transid .= $chars[rand(0, $count)];
		}
		return(strtoupper($transid));
	}

	function _getPaymentText($id)
	{
		global $AVE_DB;

		$Beschreibung = $AVE_DB->Query("
			SELECT Beschreibung
			FROM " . PREFIX . "_modul_shop_zahlungsmethoden
			WHERE Id = '" . $id . "'
		")
		->GetCell();

		return $Beschreibung;
	}



	
	function variantsCategories2($tpl_dir)
	{
	
		global $AVE_DB, $AVE_Template;
		$limit = '20';
		@$seiten = @ceil($num / $limit);
		$start = get_current_page() * $limit - $limit;
		
		$properties = array();
   		$sql = $AVE_DB->Query("SELECT * FROM ".PREFIX."_modul_shop_properties_table ORDER BY id DESC LIMIT $start,$limit");
		while($row = $sql->fetcharray()) array_push($properties,$row);

        $ids = array();
        for ($i = 0; $i < sizeof($properties); $i++) {
            if (!in_array($properties[$i]['id'], $ids)) {
                $ids[] = $properties[$i]['id'];
            }
        }	

		for ($i = 0; $i < sizeof($ids); $i++) {
                if ($i > 0) {
                    $id .= ', '.$ids[$i];
                } else {
                    $id .= $ids[$i];
                }
        }		

		if (strlen($id) > 0) {
				$def_values = array();
                $sql = $AVE_DB->Query('SELECT * FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id IN ('.$id.') ORDER BY property_id DESC, id, value');
				while($row = $sql->fetcharray()) array_push($def_values,$row);		

				for ($i = 0; $i < sizeof($def_values); $i++) {
                        for ($j = 0; $j < sizeof($properties); $j++) {
                            if ($properties[$j]['id'] == $def_values[$i]['property_id']) {
                                $properties[$j]['prp_id']      = $def_values[$i]['property_id'];
                                if ($properties[$j]['prp_def_val'] != '&nbsp;') {
                                    $properties[$j]['prp_def_val']	= $properties[$j]['prp_def_val'].$def_values[$i]['value'].'<br>';
                                } else {
                                    $properties[$j]['prp_def_val']	= $def_values[$i]['value'].'<br>';
                                }
                            }
                        }
                    }
			
            }			
		$AVE_Template->assign('variantCateg', $properties);
		//$AVE_Template->assign('ProductCategs', $this->fetchShopNavi(1));
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_variantscategs.tpl'));
	}	
	
	
	
	
	function editVariantsCategory2($tpl_dir,$id)
	{
		global $AVE_DB, $AVE_Template;
		
		$id   = (int)$id;
		if (!@$id) return FALSE;

		
	if(isset($_REQUEST['step']) && $_REQUEST['step'] == '2')
	{
		if (!@$_REQUEST['Titel'] || !@$_REQUEST['prtname'] || !@$_REQUEST['id']) return FALSE;
		
        switch ($_REQUEST['select_type']) {
        	case 0:
		        break;
        	case 1:
        	    if (!$this->is_property_name_unique($_REQUEST['name'],$id)) return FALSE;
				
		        $AVE_DB->Query('UPDATE '.PREFIX.'_modul_shop_properties_table
		        				SET property_title = "'.$_REQUEST['Titel'].'",
		        			       	property_name = "'.ereg_replace('/', '', $_REQUEST['prtname']).'",
		        					property_prefix = "'.$_REQUEST['prefix'].'",
		        					property_suffix = "'.$_REQUEST['suffix'].'",
		        					type = "'.$_REQUEST['select_type'].'"
                    			WHERE id = '.$id);

		        $AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id = '.$id);
				$AVE_DB->Query('OPTIMIZE TABLE '.PREFIX.'_modul_shop_catalog_properties_def_values');

				$def_value = $_REQUEST['def_value'];
				@$defValue   = trim($def_value[0]);
				if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values (property_id, value) VALUES ('.$id.', "'.$defValue.'")');
				
	        	break;
        	case 2:
        	    if (!$this->is_property_name_unique($_REQUEST['name'],$id)) return FALSE;
				
		        $AVE_DB->Query('UPDATE '.PREFIX.'_modul_shop_properties_table
		        				SET property_title = "'.$_REQUEST['Titel'].'",
		        			       	property_name = "'.ereg_replace('/', '', $_REQUEST['prtname']).'",
		        					property_prefix = "'.$_REQUEST['prefix'].'",
		        					property_suffix = "'.$_REQUEST['suffix'].'",
		        					type = "'.$_REQUEST['select_type'].'"
                    			WHERE id = '.$id);

		        $AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id = '.$id);
				$AVE_DB->Query('OPTIMIZE TABLE '.PREFIX.'_modul_shop_catalog_properties_def_values');

 				$def_value = $_REQUEST['def_value'];
				
				for ($i = 0; $i < sizeof($def_value); $i++) {
					$defValue   = trim($def_value[$i]);
					if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values  (property_id, value) VALUES ('.$id.', "'.$defValue.'")');
				}
			break;
			case 3:
        	    if (!$this->is_property_name_unique($_REQUEST['name'],$id)) return FALSE;
				
		        $AVE_DB->Query('UPDATE '.PREFIX.'_modul_shop_properties_table
		        				SET property_title = "'.$_REQUEST['Titel'].'",
		        			       	property_name = "'.ereg_replace('/', '', $_REQUEST['prtname']).'",
		        					property_prefix = "'.$_REQUEST['prefix'].'",
		        					property_suffix = "'.$_REQUEST['suffix'].'",
		        					type = "'.$_REQUEST['select_type'].'"
                    			WHERE id = '.$id);

		        $AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id = '.$id);
				$AVE_DB->Query('OPTIMIZE TABLE '.PREFIX.'_modul_shop_catalog_properties_def_values');

				$def_value = $_REQUEST['def_value'];
				@$defValue   = trim($def_value[0]);
				if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values (property_id, value) VALUES ('.$id.', "'.$defValue.'")');
				
	        	break;

        }		
		echo '<script>window.opener.location.reload(); window.close()</script>';
		exit;
	}
		
		
		$arr = array();
		$sql = $AVE_DB->Query('SELECT id,value FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id='.$id.' ORDER BY id');
		while($row = $sql->fetcharray()) array_push($arr, $row);

		$properties = array();
		$sql = $AVE_DB->Query('SELECT * FROM '.PREFIX.'_modul_shop_properties_table WHERE id='.$id);
		while($pro = $sql->fetchrow())
		{
			$AVE_Template->assign('id', $id);
			$AVE_Template->assign('type', $pro->type);
			$AVE_Template->assign('property_title', $pro->property_title);
			$AVE_Template->assign('property_name', $pro->property_name);
			$AVE_Template->assign('prefix', $pro->property_prefix);
			$AVE_Template->assign('suffix', $pro->property_suffix);
		}		
		$AVE_Template->assign('def_value', $arr);
		$AVE_Template->assign('def_value2', $arr);
		//$AVE_Template->assign('action', 'index.php?do=modules&action=modedit&mod=shop&moduleaction=edit_variants_category&cp='.SESSION.'&pop=1&Id=.'$id.'');
		
		$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_variantscategs_edit.tpl'));
	}
	
	
	
		
function newVariantsCategories2($tpl_dir)
{
	global $AVE_DB, $AVE_Template;
	if(isset($_REQUEST['step']) && $_REQUEST['step'] == '2')
	{
        switch ($_REQUEST['select_type']) {
        	case 0:
		        break;
        	case 1:
        	    if (!$this->is_property_name_unique($name)) return FALSE;
		        $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_table (
										property_title,
		        						property_name,
		        						property_prefix,
		        						property_suffix,
		        						type
									) VALUES (
										"'.$_REQUEST['Titel'].'",
                    					"'.ereg_replace('/', '', $_REQUEST['prtname']).'",
                    					"'.$_REQUEST['prefix'].'",
                    					"'.$_REQUEST['suffix'].'",
                    					'.$_REQUEST['select_type'].'
									)'
				);
				$property_id = $AVE_DB->insertid();						
				
				
				$def_value = $_REQUEST['def_value'];
				@$defValue   = trim($def_value[0]);
				if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values (property_id, value) VALUES ('.$property_id.', "'.$defValue.'")');
	        break;
				
        	case 2:
        	    if (!$this->is_property_name_unique($name)) return FALSE;
		        $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_table (
										property_title,
		        						property_name,
		        						property_prefix,
		        						property_suffix,
		        						type
									) VALUES (
										"'.$_REQUEST['Titel'].'",
                    					"'.ereg_replace('/', '', $_REQUEST['prtname']).'",
                    					"'.$_REQUEST['prefix'].'",
                    					"'.$_REQUEST['suffix'].'",
                    					"'.$_REQUEST['select_type'].'"
									)'
				);
				$property_id = $AVE_DB->insertid();	

 				$def_value = $_REQUEST['def_value'];
				
				for ($i = 0; $i < sizeof($def_value); $i++) {
					$defValue   = trim($def_value[$i]);
					if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values  (property_id, value) VALUES ('.$property_id.', "'.$defValue.'")');
				}
			break;
			
			
			
			
        	case 4:
        	    if (!$this->is_property_name_unique($name)) return FALSE;
		        $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_table (
										property_title,
		        						property_name,
		        						property_prefix,
		        						property_suffix,
		        						type
									) VALUES (
										"'.$_REQUEST['Titel'].'",
                    					"'.ereg_replace('/', '', $_REQUEST['prtname']).'",
                    					"'.$_REQUEST['prefix'].'",
                    					"'.$_REQUEST['suffix'].'",
                    					"'.$_REQUEST['select_type'].'"
									)'
				);
				$property_id = $AVE_DB->insertid();	

 				$def_value = $_REQUEST['def_value'];
				
				for ($i = 0; $i < sizeof($def_value); $i++) {
					$defValue   = trim($def_value[$i]);
					if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values  (property_id, value) VALUES ('.$property_id.', "'.$defValue.'")');
				}
			break;			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
        	case 3:
        	    if (!$this->is_property_name_unique($name)) return FALSE;
		        $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_table (
										property_title,
		        						property_name,
		        						property_prefix,
		        						property_suffix,
		        						type
									) VALUES (
										"'.$_REQUEST['Titel'].'",
                    					"'.ereg_replace('/', '', $_REQUEST['prtname']).'",
                    					"'.$_REQUEST['prefix'].'",
                    					"'.$_REQUEST['suffix'].'",
                    					'.$_REQUEST['select_type'].'
									)'
				);
				$property_id = $AVE_DB->insertid();						
				
				
				$def_value = $_REQUEST['def_value'];
				@$defValue   = trim($def_value[0]);
				if ($defValue) $AVE_DB->Query('INSERT INTO '.PREFIX.'_modul_shop_properties_def_values (property_id, value) VALUES ('.$property_id.', "'.$defValue.'")');
	        break;			
        }		
		echo '<script>window.opener.location.reload(); window.close()</script>';
	}
		
	$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'shop_variantscategs_edit.tpl'));
}
	
	
	function is_property_name_unique($name, $id = 0) {
	global $AVE_DB, $AVE_Template;
        $sql = $AVE_DB->Query('SELECT count(*) as cnt FROM '.PREFIX.'_modul_shop_properties_table WHERE property_name = "'.$name.'"'.(($id) ? ' AND id <> '.$id : ''));
		$row = $sql->fetchrow();
		return intval($row->cnt) == 0;
	}		
	
	
	
	
	function deleteVariantsCategory2($id)
	{
	global $AVE_DB, $AVE_Template;
		$id   = (int)$id;
		if (!@$id) return FALSE;
        $AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_properties WHERE property_id='.$id);
    	$AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id='.$id);
        $AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_property_types_images WHERE property_id='.$id);
		$AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_property_values WHERE property_id='.$id);
		$AVE_DB->Query('DELETE FROM '.PREFIX.'_modul_shop_properties_table WHERE id='.$id);
		header("Location:index.php?do=modules&action=modedit&mod=shop&moduleaction=variants_categories2&cp=" . SESSION);
		exit;
	}
	
	
	
	
	
	
	
	
	


	
	
	
	
	
	
	
	
	
	
	
	
function array_js($tpl_dir, $KatId='', $product_id='')
{
	global $AVE_DB, $AVE_Template;
			
	if ($_SESSION['REQUEST']['KatId'] != $KatId) $_SESSION['REQUEST'] = '';	
	
	
	$product_id = $product_id ? (int)$product_id : '';
	
	if (@$KatId) {
		$group_id = (int)$KatId;

	if (!$group_id) {
		$AVE_Template->assign('ar', '');
		$AVE_Template->assign('kat', $group_id);
		echo $AVE_Template->fetch($tpl_dir . 'shop_test.tpl');
		exit;
	}


		$sql = $AVE_DB->Query('SELECT * FROM '.PREFIX.'_modul_shop_properties WHERE group_id='.$group_id.' ORDER BY ord');
		while($row = $sql->fetchrow())
		{
			$array[] = $row->property_id;
		}
		
		
	if (is_array($array)) {
		
			$str = implode(",", $array);

			if (@$product_id) {
				$sql = $AVE_DB->Query('SELECT KatId FROM '.PREFIX.'_modul_shop_product WHERE Id = '.$product_id);
				$row = $sql->fetchrow();
				if ($group_id != $row->KatId) $product_id = FALSE;
            }

            if (@$product_id) {
                $sql = $AVE_DB->Query('SELECT property_id, value FROM '.PREFIX.'_modul_shop_property_values WHERE product_id = '.$product_id.' ORDER BY property_id');
				while($row = $sql->fetchrow()) $prod_val[$row->property_id] = $row->value;
            }

			$def_val = array();
            $sql = $AVE_DB->Query('SELECT property_id, value FROM '.PREFIX.'_modul_shop_properties_def_values WHERE property_id IN ('.$str.') ORDER BY property_id, id, value');
			while($row = $sql->fetchrow())
			{
				$def_val1['property_id'] = $row->property_id;
				$def_val1['value'] = $row->value;
				array_push($def_val, $def_val1);
			}
			
//print_r($_SESSION['REQUEST']);
//print_r($_SESSION['REQUEST']['prp_val'][$def_val[$i]['property_id']]);
//print_r($def_val[$i]['value']);					
			//print_r($def_val_input[$def_val[$i]['property_id']]);

            for ($i = 0; $i < sizeof(@$def_val); $i++) {
			
                if (@$def_val_input[$def_val[$i]['property_id']] && ($def_val_input[$def_val[$i]['property_id']]['type'] == 'select')) {
					$sess = (is_array($_SESSION['REQUEST'])) ? $_SESSION['REQUEST']['prp_val'][$def_val[$i]['property_id']] == $def_val[$i]['value'] : '' ;
					$selected_2 = '';
                    if (@$prod_val[$def_val[$i]['property_id']] == $def_val[$i]['value'] || $sess) $selected_2 = ' selected';
                    $def_val_input[$def_val[$i]['property_id']]['value'] = $def_val_input[$def_val[$i]['property_id']]['value'].'<option value="'.$def_val[$i]['value'].'"'.@$selected_2.'>'.$def_val[$i]['value'].'</option>';
                    $def_val_input[$def_val[$i]['property_id']]['type']  = 'select';
                    $def_val_input[$def_val[$i]['property_id']]['id']  = $def_val[$i]['property_id'];
                
				} elseif(@$def_val_input[$def_val[$i]['property_id']] && ($def_val_input[$def_val[$i]['property_id']]['type'] != 'select')) {
                    
					$sess2 = (is_array($_SESSION['REQUEST'])) ? $_SESSION['REQUEST']['prp_val'][$def_val[$i]['property_id']] == $def_val_input[$def_val[$i]['property_id']]['value'] : '' ;
					$sess3 = (is_array($_SESSION['REQUEST'])) ? $_SESSION['REQUEST']['prp_val'][$def_val[$i]['property_id']] == $def_val[$i]['value'] : '' ;
										
					if (@$prod_val[$def_val[$i]['property_id']] == $def_val_input[$def_val[$i]['property_id']]['value'] || $sess2) {
                        $selected_1 = ' selected';
                    } elseif (@$prod_val[$def_val[$i]['property_id']] == $def_val[$i]['value'] || $sess3) {
                        $selected_2 = ' selected';
                    }
                    $def_val_input[$def_val[$i]['property_id']]['value'] = 
					'<option value="">-- Выберите значение --</option>'.
					'<option value="'.$def_val_input[$def_val[$i]['property_id']]['value'].'"'.@$selected_1.'>'.$def_val_input[$def_val[$i]['property_id']]['value'].'</option>'.
					'<option value="'.$def_val[$i]['value'].'"'.@$selected_2.'>'.$def_val[$i]['value'].'</option>';
                    $def_val_input[$def_val[$i]['property_id']]['type']  = 'select';
                    $def_val_input[$def_val[$i]['property_id']]['id']  = $def_val[$i]['property_id'];
					
// тут я плять чуть не умер.... гори оно синем пламенем это динамическое подставление параметров ! 
										
                } else {
				
                    $def_val_input[$def_val[$i]['property_id']]['value'] = $def_val[$i]['value'];
                    $def_val_input[$def_val[$i]['property_id']]['type']  = 'input';
                    $def_val_input[$def_val[$i]['property_id']]['id']  = $def_val[$i]['property_id'];
					
					
					
                }
            }
			
			
			
			
			
//$_SESSION['REQUEST']['prp_val'][$def_val_input[$id]['id']]
//(SELECT ord FROM '.PREFIX.'_modul_shop_properties WHERE group_id='.$group_id.')

//exit;
			$sql = $AVE_DB->Query('SELECT properties_table.*, properties.ord  
			FROM '.PREFIX.'_modul_shop_properties_table as properties_table, '.PREFIX.'_modul_shop_properties as properties 
			WHERE properties_table.id IN ('.$str.') AND properties_table.id = properties.property_id
			GROUP BY properties_table.id 
			ORDER BY properties.ord  ASC');
			while($row = $sql->fetchrow())
			{
			//	print_r($def_val_input[$id]['value']);
				$id = $row->id;
				$ar[$id]['id'] 						= $id;
				$ar[$id]['property_title'] 			= $row->property_title;
				$ar[$id]['property_prefix'] 	  	= $row->property_prefix;
				$ar[$id]['property_suffix'] 	  	= $row->property_suffix;
                $ar[$id]['other_picture'] 	  		= (is_array($_SESSION['REQUEST'])) ? $_SESSION['REQUEST']['prp_val'][$def_val_input[$id]['id']] : '';
                if ($row->type == '1' && !$prod_val[$id]) {
				
                    $ar[$id]['property_def_value'] 	= $def_val_input[$id]['value'];
                    $ar[$id]['property_type']      	= 'input';
                } 
				elseif ($row->type == '2' ) {
				
                    $ar[$id]['property_def_value'] 	= $def_val_input[$id]['value'];
                    $ar[$id]['property_type']      	= 'select';
				} 
				elseif ($row->type == '4' ) {
				
                    $ar[$id]['property_def_value'] 	= $def_val_input[$id]['value'];
                    $ar[$id]['property_type']      	= 'many_checkbox';
				
                } 
				elseif ($row->type == '3' && !$prod_val[$id]) {
				
                    $ar[$id]['property_def_value'] 	= $def_val_input[$id]['value'];
                    $ar[$id]['property_type']      	= 'checkbox';
                    $ar[$id]['checked']      		= (is_array($_SESSION['REQUEST'])) ? $_SESSION['REQUEST']['prp_val'][$def_val_input[$id]['id']] : ($def_val_input[$id]['value'] == '1') ? '1' : '' ;
					
                } 
				elseif (@$prod_val[$id] && ($row->type == '1')) {
                    $ar[$id]['property_def_value'] 	= $prod_val[$id];
					$ar[$id]['property_type']      	= 'input';

                }
				elseif (@$prod_val[$id] && ($row->type == '3')) {
                    $ar[$id]['property_def_value'] 	= $prod_val[$id];
                    $ar[$id]['property_type']      	= 'checkbox';
                    $ar[$id]['checked']      		= (is_array($_SESSION['REQUEST'])) ? $_SESSION['REQUEST']['prp_val'][$def_val_input[$id]['id']] : ($prod_val[$id] == '1') ? '1' : '' ;

                }
			}

			
			$string = 'var propertis = new Array (';
			$c = sizeof($array);
			for($i=0; $i < $c; $i++) {
				$string .= $ar[$array[$i]]['id'].', "'.$ar[$array[$i]]['property_title'].'", "'
				    .$ar[$array[$i]]['property_prefix'].'", "'.$ar[$array[$i]]['property_suffix']
				    .'", "'.$ar[$array[$i]]['property_def_value'].'", "'
				    .$ar[$array[$i]]['property_type'].'", "'.$ar[$array[$i]]['other_picture'].'"';
				if ($c > ($i+1)) {
					$string .= ', ';
				} else {
					$string .= ');';
				}
			}
			

		
		
	} else {
		$AVE_Template->assign('ar', '');
		$AVE_Template->assign('kat', $group_id);
		echo $AVE_Template->fetch($tpl_dir . 'shop_test.tpl');
		exit;
	}
	
		$AVE_Template->assign('ar', $ar);			
		echo $AVE_Template->fetch($tpl_dir . 'shop_test.tpl');		
		exit;		
	} else {
		$AVE_Template->assign('ar', '');
		$AVE_Template->assign('kat', $group_id);
		echo $AVE_Template->fetch($tpl_dir . 'shop_test.tpl');
		exit;
}
exit;
}	
		
	
	
	
	
	
	
	
	
	
	
	




	
	
	
}

?>